Luke Ryan Jernejcic

Rethrow An Exception in C#

May 11, 2012

So generally, when I want to re-throw an exception that I caught in C#, I just throw a new exception like this:

try {
    // ...
} catch (Exception ex) {
    // ...
    throw new Exception(ex.message); // or throw new Exception("", ex.message);
}

This just never sat well with me, so today I decided to figure out if there was a better way to handle this. Seems like there just had to be.

Shoot, it is so simple!

try {
    // ...
} catch (Exception ex) {
    // ...
    throw (ex);
}

throw (ex); will re-throw the exception that was caught as if it was not caught.

If by chance you didn’t catch the exception object, you can still re-throw it like this:

try {
    // ...
} catch {
    // ...
    throw;
}

I am in shock that all these years I was unaware of this. Enjoy! And thanks to the Microsoft docs, which I should visit more often.


Written by Luke Ryan Jernejcic who lives and works in Austin Texas building useful things. Follow him on Twitter