[英]Is there a reason to throw an exception twice?
Debugging production code I came across something I had not seen before and am not aware of a valid purpose. 调试生产代码我遇到了一些我以前从未见过的东西,并且我没有意识到有效的目的。 In several methods of one of our controllers we have try-catch blocks.
在我们的一个控制器的几种方法中,我们有try-catch块。 The interesting part is there are 2 throw statements in one of the catches.
有趣的是,其中一个捕获中有2个抛出语句。
Is there any reason to have 2 throw statements? 有没有理由有2个抛出语句? If so, in what circumstance(s) does that make sense?
如果是这样,在什么情况下这是有道理的?
try
{
//statements
}
catch (SoapException se)
{
//Log statement
return null;
}
catch (Exception ex)
{
//Log statement
throw;
throw;
}
No there is no reason to throw
twice. 没有理由
throw
两次。 The second throw
will never be reached. 永远不会达到第二次
throw
。
It is also similar to having 它也类似于
public int GetNumber()
{
return 1;
return 2; // Never reached
}
Update 更新
Resharper is a great tool to check things like this. Resharper是一个很好的工具来检查这样的事情。
In this case it will grey out the second throw
and tell you it is unreachable. 在这种情况下,它将灰显第二次
throw
并告诉你它无法到达。
There is absolutely no purpose in throwing an exception twice in a row. 连续两次抛出异常绝对没有任何意义。 The second
throw
can never be reached, and it is most likely a typo, or code that was edited, but never completed and since forgotten about. 永远无法达到第二次
throw
,并且它很可能是一个错字,或编辑过的代码,但从未完成,因此被遗忘。
In the example you showed, there would be no purpose to the two throw statements. 在您展示的示例中,两个throw语句没有任何意义。 As soon as the first one is hit it starts to work its way back up the call stack until it is caught.
一旦第一个被击中,它就会开始恢复调用堆栈,直到它被捕获为止。 The only way for two to make any differance is if the first one was conditional or caught before he second one was hit.
两个人做出任何分歧的唯一方法是,如果第一个是有条件的,或者在第二个被击中之前被捕获。
try
{
//statements
}
catch (SoapException se)
{
//Log statement
return null;
}
catch (Exception ex)
{
//Log statement
if (condition)
throw;
throw;
}
or 要么
try
{
//statements
}
catch (SoapException se)
{
//Log statement
return null;
}
catch (Exception ex)
{
//Log statement
try
{
throw;
}
catch (Exception)
{
//Handle first thrown exception.
}
throw;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.