如何抛出异常

How to throw an exception

throw;throw ex; 之间做出选择的最佳做法是什么?有没有?例如,关于这个简单的片段:

try{
    // some code
} catch (Exception ex) {
    // some catcher code
    // throw; ?
    // or
    // throw ex; ?
    // how to decide which one?
}

我知道上面两者的区别。我如何决定使用其中之一?是否有做出更好选择的最佳实践?

您应该使用 throw; 重新抛出原始异常(使用原始堆栈跟踪)或使用 throw new MyException(..., ex); 抛出您自己的异常,这可能会提供额外的信息 将内部异常设置为 ex.

如果您没有任何其他信息,请使用 throw;

如果您只是捕获异常来进行清理,那么请改用 try {...} finally {...}

It's very simple.

是否要保留堆栈跟踪以准确查看异常发生的位置?然后使用throw。如果您根本不使用 catch,就会像这样。

您只关心当前方法的调试信息吗?然后使用 throw ex.

演示:

static void Main(string[] args)
{
    try
    {
        Test();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

static void Test()
{
    try
    {
        // long lambda chain
        new Action(() => new Action(() => new Action(() => { throw new InvalidOperationException(); })())())();
    }
    catch (Exception ex)
    {
        //throw;
        //throw ex;
    }
}

throw 将保留堆栈跟踪:

System.InvalidOperationException: Operation is not valid due to the current state of the object.
    at ConsoleApplication.Program.<>c.<Test>b__1_2() in ConsoleApplication\Program.cs:line 22
    at ConsoleApplication.Program.<>c.<Test>b__1_1() in ConsoleApplication\Program.cs:line 22
    at ConsoleApplication.Program.<>c.<Test>b__1_0() in ConsoleApplication\Program.cs:line 22
    at ConsoleApplication.Program.Test() in ConsoleApplication\Program.cs:line 26
    at ConsoleApplication.Program.Main(String[] args) in ConsoleApplication\Program.cs:line 13

throw ex 将重置堆栈跟踪:

System.InvalidOperationException: Operation is not valid due to the current state of the object.
    at ConsoleApplication.Program.Test() in ConsoleApplication\Program.cs:line 27
    at ConsoleApplication.Program.Main(String[] args) in ConsoleApplication\Program.cs:line 13

至于最佳实践 - 选择is usually throw。作为开发人员,您希望获得尽可能多的信息。 throw ex 是对应的 - 有些信息是隐藏的,但也许你想隐藏它,谁知道呢?