Reputation: 47
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. The interesting part is there are 2 throw statements in one of the catches.
Is there any reason to have 2 throw statements? 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;
}
Upvotes: 2
Views: 1631
Reputation: 1411
No there is no reason to throw
twice. The second throw
will never be reached.
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.
In this case it will grey out the second throw
and tell you it is unreachable.
Upvotes: 10
Reputation: 26362
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.
Upvotes: 3
Reputation: 1279
In the example you showed, there would be no purpose to the two throw statements. 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;
}
Upvotes: 3