什么是重新扔在C#中的异常的正确方法?异常、正确、方法

2023-09-02 01:18:27 作者:蔓语思

我有一个问题要问你,源于我的伙伴做的事情不同的方式比我好。

I have a question for you that stems from my partner doing things a different way than I do.

是更好地做到这一点:

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw;
}

或者这样的:

or this:

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw ex;
}

难道他们做同样的事情?比另一种更好呢?

Do they do the same thing? Is one better than the other?

推荐答案

您应该始终使用下面的语法来重新抛出异常,否则你会踩堆栈跟踪:

You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:

throw;

如果您打印的痕迹,从扔恩造成,你会发现它结束在该声明中,而不是在例外的真正根源。

If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.

基本上,它应该被视为刑事犯罪用扔恩。

Basically, it should be deemed a criminal offense to use "throw ex".