Ahmad Ahmad - 4 months ago 34
C# Question

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();
}

Answer

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.

Comments