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

Nick Raphael @nickraphael

About: Brought to you by Nick Raphael. Fullstack azure architect and tech lead. Currently neck deep in dotnet core - azure stack - microservices.

Location:
Sydney, Australia
Joined:
Oct 21, 2019

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

Publish Date: Apr 6 '20
7 1

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

Comments 1 total

  • Davide Bellone
    Davide BelloneApr 6, 2020

    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!

Add comment