重新抛出异常的正确方法

elc*_*e23 0 c# exception-handling

我在 C# 中有以下方法:

void Method1()
{
    try
    {
        Method2();
    }
    catch(Method2Exception ex)
    {
        //Log error
    }
}

void Method2()
{
    if(error)
    {
        throw(new Method2Exception("error"));
    }

    //Do something and call method3
    try
    {
        Method3();
    }
    catch(Method3Exception)
    {
        //??
    }
}

void Method3()
{
    //Do something
    if(error)
    {
        throw(new Method3Exception("error"));
    }
}
Run Code Online (Sandbox Code Playgroud)

Method3 它将被不同的方法调用,它返回 Method3Exception,我需要将异常从 Method2 重新抛出到 Method1,但我不想在 Method1 上捕获 Method3Exception。最好的方法是什么?

有什么建议

Zei*_*kki 5

术语(重新)抛出通常是指将异常抛出回调用者保留堆栈跟踪(其中包含异常发生的确切位置)。这可以在throw;不指定异常操作数的情况下使用throw ex

try
{
    Method3();
}
catch(Method3Exception)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您只是要在该方法中添加一个没有任何内容的 throw 。这是没用的,只需删除 try..catch 并且异常将传播到调用者,这是默认行为。

文档

可以在 catch 块中使用 throw 语句来重新抛出 catch 块捕获的异常。在这种情况下,throw 语句不接受异常操作数。