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".