在 C# 中重新引发异常的正确方法是什么?
- 作者: 打响新年第一炮
- 来源: 51数据库
- 2023-02-08
问题描述
这样做更好吗:
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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
