Rethrowing an exception within a catch block

suggest change

Within a catch block, the throw keyword can be used on its own, without an exception value, to rethrow the exception that was just caught. Rethrowing lets that exception continue up the handling chain and keeps its call stack and other 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, throw ex is not desirable. Later handlers that inspect the stack trace will only see calls as far back as throw ex. Omitting ex and using throw alone lets the original exception bubble up.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents