2011-04-05 55 views
3

我有一個以下的C#場景 我必須處理派生類中實際發生的基類中的異常。 我的基類看起來是這樣的:處理基類異常

public interface A 
{ 
    void RunA(); 
} 
public class Base 
    { 
     public static void RunBase(A a) 
     { 
      try 
      { 
       a.RunA(); 
      } 
      catch { } 
     } 
    } 

派生類如下:

public class B: A 
{ 
     public void RunA() 
     { 
      try 
      { 
       //statement: exception may occur here 
      } 
      catch{} 
    } 
} 

我要處理的例外,可以說除了C,發生在B(在//聲明以上)。 異常處理部分應該寫入RunBase中的基類catch中。如何才能做到這一點?

回答

6
public class Base 
{ 
    public static void RunBase(A a) 
    { 
     try 
     { 
      a.RunA(); 
     } 
     catch(SomeSpecialTypeOfException ex) 
     { 
      // Do exception handling here 
     } 
    } 
} 

public class B: A 
{ 
    public void RunA() 
    { 
     //statement: exception may occur here 
     ... 

     // Don't use a try-catch block here. The exception 
     // will automatically "bubble up" to RunBase (or any other 
     // method that is calling RunA). 
    } 
} 
0

這怎麼辦?

你是什麼意思? 只需從RunA刪除try-catch塊。

說了這麼多,你需要確保A類知道如何處理異常,這包括它精簡到UI,記錄,...這其實是罕見一個基類。處理異常通常發生在UI級別。

0
public class B: A 
{ 
     public void RunA() 
     { 
      try 
      { 
       // statement: exception may occur here 
      } 
      catch(Exception ex) 
      { 
       // Do whatever you want to do here if you have to do specific stuff 
       // when an exception occurs here 
       ... 

       // Then rethrow it with additional info : it will be processed by the Base class 
       throw new ApplicationException("My info", ex); 
      } 
    } 
} 

您還可能想拋出異常(原樣使用throw)。

如果您不需要在這裏處理任何東西,請不要嘗試{} catch {},讓異常自行冒泡並由Base類處理。

0

只要從類B中刪除try catch,如果發生異常,它將自動打開調用鏈直到它被處理。在這種情況下,您可以使用現有的try catch塊在RunBase中處理異常。

雖然在你的例子B不是從你的基類Base派生。如果你真的想要處理在父類派生類中拋出異常的情況,你可以嘗試類似於:

public class A 
{ 
    //Public version used by calling code. 
    public void SomeMethod() 
    { 
     try 
     { 
      protectedMethod(); 
     } 
     catch (SomeException exc) 
     { 
      //handle the exception. 
     } 
    } 

    //Derived classes can override this version, any exception thrown can be handled in SomeMethod. 
    protected virtual void protectedMethod() 
    { 
    } 

} 

public class B : A 
{ 
    protected override void protectedMethod() 
    { 
     //Throw your exception here. 
    } 
}