Consider the following code:
try{
....
} catch(Exception) {
return null;
throw;
}
Does it make any sense?
Normally, if you put any codes after return, Visual Studio marks that as unreachable code, but for this case, it does not. Is there a reason for that?
Edit
As a complement to the question, I want to ask another one.
What happens if I throw the exception in the finally block, after return?
try{
....
} catch(Exception) {
return null;
} finally {
throw new Exception();
}
The throw
after return
is never executed. The exception is not thrown
to the caller. It is an unreachable code.
It doesn't make any sense, a method that throws an exception doesn't return anything to the caller (except the exception itself) . So just throw.
try
{
// return something valid
}
catch(Exception)
{
throw;
}
As for why it is not marked by Visual Studio as unreachable, I think it is a bug.
If you throw an exception in the finally block, the exception bubbles up the stack to find a catch and the value is not returned.
It makes no sense at all to put any code after a return
-statement. It can´t be executed at all, be it a valid statement or like in your case an exception. With return
you go up the execution-stack and do not come back, so there is no way for the application to examine the code after that single return
statement.
You should either return a specific value or throw an exception, doing both won´t work. Having said this both a return
as well as a throw
statement will leave the current method and go back to the calling-method.
As an aside there´s also the yield return
. This works a bit different, as it means "return the next element from the iterator-method".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With