.NET Framework Exceptions Rethrowing an exception within a catch block

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Within a catch block the throw keyword can be used on its own, without specifying an exception value, to rethrow the exception which was just caught. Rethrowing an exception allows the original exception to continue up the exception handling chain, preserving its call stack or associated data:

try {...}
catch (Exception ex) {
  // Note: the ex variable is *not* used
  throw;
}

A common anti-pattern is to instead throw ex, which has the effect of limiting the next exception handler's view of the stack trace:

try {...}
catch (Exception ex) {
  // Note: the ex variable is thrown
  //  future stack traces of the exception will not see prior calls
  throw ex;  
}

In general using throw ex isn't desirable, as future exception handlers which inspect the stack trace will only be able to see calls as far back as throw ex. By omitting the ex variable, and using the throw keyword alone the original exception will "bubble-up".



Got any .NET Framework Question?