什么是重新扔在C#中的异常的正确方法? [英] What is the proper way to re-throw an exception in C#?

查看:166
本文介绍了什么是重新扔在C#中的异常的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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".

这篇关于什么是重新扔在C#中的异常的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆