Search code examples
c#exceptiontry-catchrethrow

Try catch and re-throw exception


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?


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.