繁体   English   中英

处理基类异常

[英]Handle base class exception

我有一个以下的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中。 如何才能做到这一点?

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-catchRunA

话虽如此,您需要确保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 {},让异常自己冒泡并由Base类处理。

只需从类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.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM