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

Nick Raphael - Apr 6 '20 - - Dev Community

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;'.

. . . . . . . . . . . . . . . . . . . . . . . . . .