DEV Community

Cover image for c# quicky. Should we 'throw;' or 'throw e;'?
Nick Raphael
Nick Raphael

Posted on

c# quicky. Should we 'throw;' or 'throw e;'?

This is a bit of an oldie. Very old, in fact, since this question has been around since c# was born. And likely before that for other languages.

What's the difference between these code snippets?

try
{
  ...some code
}
catch (Exception)
{
  throw;
}

try
{
  ...some code
}
catch (Exception e)
{
  throw e;
}
Enter fullscreen mode Exit fullscreen mode

Well, it's all about where the exception originates and what happend to the stacktrace...

throw : Using a "throw" statement preserves the original error stack information. In exception handling "throw" with empty parameter is also called re-throwing the last exception.

throw e : Using a "throw e" statement, the stack trace of exception will be replaced with a stack trace starting at the re-throw point. It is used to intentionally hide stack trace information.

Most of the time you will want to 'throw;'.

Top comments (1)

Collapse
 
bellonedavide profile image
Davide Bellone

I've seen many mid-level devs doing the wrong thing. It's a small change that can really help while debugging and analyzing the logs!