Advertisement
Intermediate C#, Exception Handling

Why does 'throw;' (bare throw) preserve the original stack trace, while 'throw ex;' does not?

Short answer

'throw;' re-throws the CURRENT exception exactly as caught, preserving its original stack trace all the way back to where it was FIRST thrown; 'throw ex;' treats it as throwing a NEW exception from THIS point, overwriting the stack trace and losing the original throw location —…

Save C# mock interview
Advertisement
AModel answer
'throw;' re-throws the CURRENT exception exactly as caught, preserving its original stack trace all the way back to where it was FIRST thrown; 'throw ex;' treats it as throwing a NEW exception from THIS point, overwriting the stack trace and losing the original throw location — making the bare 'throw;' the correct choice when re-throwing after logging or partial handling.
try {
  DoSomethingRisky();
} catch (Exception ex) {
  LogError(ex);
  throw;     // CORRECT: preserves the original stack trace
  // throw ex; // WRONG: resets the stack trace to this line
}
Real-world example
Logging an exception's details before re-throwing it, without losing the diagnostic value of the original stack trace.
Likely follow-ups
  • Is there any legitimate reason you'd deliberately want to use 'throw ex
  • ' instead of bare 'throw
  • '?
Related topics