Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Rethrow exception in catch block, after return

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();
}
like image 698
Ahmad Avatar asked Feb 06 '23 10:02

Ahmad


2 Answers

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.

Edit:

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.

like image 61
Zein Makki Avatar answered Feb 09 '23 15:02

Zein Makki


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".

like image 24
MakePeaceGreatAgain Avatar answered Feb 09 '23 16:02

MakePeaceGreatAgain