这样做是否更好:
try
{
...
}
catch (Exception ex)
{
...
throw;
}
Or this:
try
{
...
}
catch (Exception ex)
{
...
throw ex;
}
他们做同样的事情吗?这个比那个好吗?
您应该始终使用以下语法来重新引发异常。否则你会踩踏堆栈跟踪:
throw;
如果打印由以下结果产生的跟踪throw ex
,您会看到它在该语句处结束,而不是在异常的真正来源处结束。
基本上,使用该行为应被视为刑事犯罪throw ex
.
如果需要重新抛出来自其他地方的异常(AggregateException、TargetInitationException)或可能来自另一个线程,您也不应该直接重新抛出它。而是有异常调度信息 https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo保留所有必要的信息。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)