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

What is the proper way to rethrow an exception in C#?(在 C# 中重新引发异常的正确方法是什么?)
本文介绍了在 C# 中重新引发异常的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这样做更好吗:

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

或者这个:

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

他们做同样的事情吗?一个比另一个好?

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

推荐答案

您应该始终使用以下语法重新引发异常.否则你会踩到堆栈跟踪:

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

throw;

如果您打印由 throw ex 产生的跟踪,您会看到它以该语句结束,而不是异常的真正来源.

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.

基本上,使用throw ex应该被视为刑事犯罪.

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

如果需要重新抛出来自其他地方(AggregateException、TargetInvocationException)或可能来自另一个线程的异常,您也不应该直接重新抛出它.而是有 ExceptionDispatchInfo 保留所有必要的信息.

If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the ExceptionDispatchInfo that preserves all the necessary information.

try
{
    methodInfo.Invoke(...);
}
catch (System.Reflection.TargetInvocationException e)
{
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
    throw; // just to inform the compiler that the flow never leaves the block
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)