Question

I saw some code the other day in one of our projects that uses a try catch and re-throws the caught exception like this:

try
{
    exceptionProneCode();
}
catch(Exception ex)
{
    throw ex;
}

Nothing else was done with the exception in the catch block so I'm not even sure why it's re-thrown. I can't see any benefit to actually throwing the same exception again and doing nothing with the exception.

If you re-throw an exception that's caught in the catch block, how does C# handle this? Does it get stuck in an infinite throw/catch loop? Or does it eventually leave the try catch?

Was it helpful?

Solution

Consider these two models:

1- By re-throwing ex:

catch(Exception ex)
{
    throw ex;
}

you loose StackTrace. If the exception is logged somewhere the StackTrace containing immediate frames of the call stack (history of method calls) is lost.

2- In contrast by throw:

catch(Exception ex)
{
    // do something here
    throw;
}

you maintain StackTrace. You can do additional processing and then re-throw the exception without loosing the trace string.

OTHER TIPS

It continues to throw the exception up the calls stack. One thing that this piece of code does that is different from if you didn't catch the exception, it will reset the exception location (call stacks, line #, etc) to where you re-threw the exception, so you won't have the location where the original exception was thrown.

If you're not going to actually do something in the catch block I would recommend not catching, or at the very least rethrowing with just a throw instead of throw ex.

It throws the exception to the caller. But it handles it here so it doesn't throw an unhandled exception. However, honestly, I don't see the benefit of this. Just let it throw the exception. Why? Because an exception is only unhandled if the entire call stack above it doesn't have a try ... catch. This isn't doing anything useful.

Does it get stuck in an infinite throw/catch loop? Or does it eventually leave the try catch?

No. Yes.

The code provides no benefit and does harm to debugging as noted by everyone else.

A good catch block will catch a specific expected issue and log & continue (the problem doesn't indicate the applications state is corrupt), log and halt (because the application is now in an unknown state and continuing could wreck more harm), do something else (e.g. fall back to an equivalent technology/algorithm), wait and try again.

The default is that something is unexpected, should be logged and the application should be stopped-- either abandoning the page or if a winforms app, revert back to a known state if possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top