Rethrowing exceptions, the right way

Published 02-21-2005 3:04 PM | jokiz

I have read the Exception Handling Best Practices article in .NET in CodeProject and all this time I thought that rethrowing exceptions is this way:

[code language="C#"]

try
{
    // Some code that throws an exception
}
catch (Exception ex)
{
    // some code that handles the exception
    throw ex;
}
[/code]

I just learned that it should have been this way:

[code language="C#"]
try
{
    // Some code that throws an exception
}
catch (Exception ex)
{
    // some code that handles the exception
    throw;
}
[/code]

Reason:  Stack Trace Preservation

Currently, I still don’t have a solid understanding on .NET Exceptions, its internals, etc.  I still have to do a number of readings about them…

Comments

# Supremo said on August 17, 2005 9:51 PM:

You can also do this way

try{

}
catch{throw;}

# jokiz said on September 14, 2005 6:11 PM:

i assume that you will also have something to do inside the catch block aside from rethrowing because there's no sense of catching it in the first place.

Note that a non-parameterized catches all the other exceptions not defined in managed code.