2011-04-05 58 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. 
    } 
}