Skip to content
loading...
Cover image for c# quicky.  Should we 'throw;' or 'throw e;'?

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

nickraphael profile image Nick Raphael twitter logo github logo ・1 min read

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;
}

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

twitter logo DISCUSS (1)
Discussion
markdown guide
 

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!

Classic DEV Post from Aug 1 '19

Which dev.to loading GIF do you prefer?

I made some dev.to loading gifs

Nick Raphael profile image
Brought to you by Nick Raphael. Fullstack azure architect and tech lead. Currently neck deep in angular - dotnet core - azure stack.