Search code examples
c#anti-patterns

try{} catch(Exception e){} VS try{} catch(Exception e){ throw;} - What the difference?


I got here that the next code is anti-pattern. Is it right?

try
{
//something
} 
catch(Exception e)
{
//something
}

And why better to use

try
{
//something
} 
catch(Exception e)
{
 //something
 throw;
}

?

I got that second variant is using for re-throwing exception (logging for example), but if I need re-throw the same exception why not use the next code?

try
{
//something
} 
catch(Exception e)
{
 //something
 throw e;
}

Solution

  • This will re-throw the same exception and keep the stack trace. This will make debugging easier.

    catch(Exception e)
    {
     //something
     throw;
    }
    

    This will rethrow the exception, but you'll lose the stack trace.

    catch(Exception e)
    {
     //something
     throw e;
    }
    

    This will silently swallow the exception. You only want to do this when you're catching a specific exception rather than Exception. You should generally have a good reason for doing so.

    try
    {
    //something
    } 
    catch(Exception e)
    {
    //something
    }