C# 处理基类异常
我有一个C#场景- 我必须处理基类中实际发生在派生类中的异常。 我的基类如下所示:C# 处理基类异常,c#,inheritance,exception-handling,C#,Inheritance,Exception Handling,我有一个C#场景- 我必须处理基类中实际发生在派生类中的异常。 我的基类如下所示: public interface A { void RunA(); } public class Base { public static void RunBase(A a) { try { a.RunA(); } catch { }
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中编写。如何做到这一点
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).
}
}
如何做到这一点
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).
}
}
你什么意思只需从RunA
中删除try catch
块即可
话虽如此,您需要确保类A知道如何处理异常,这包括将异常简化为UI、日志记录等。。。对于基类来说,这实际上是非常罕见的。处理异常通常发生在UI级别
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
)
如果您不需要在此处处理任何内容,请不要放置try{}catch{},让异常自行冒泡并由基类处理。只需从类B中删除try-catch,如果发生异常,它将启动调用链,直到处理完为止。在这种情况下,可以使用现有的try-catch块在RunBase中处理异常 尽管在您的示例中,B不是从基类派生的。如果您确实想处理在父类的派生类中引发异常的情况,可以尝试以下操作:
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.
}
}