throw vs throw ex in C#: Why throw ex Destroys Your Stack Trace (video)

In C#, throw ex resets the stack trace to the current method, so you lose where the error really happened. See the difference with examples, when to wrap exceptions, and how to catch throw ex automatically.

Read the full article

Transcript

throw vs throw ex in C#: Why throw ex Destroys Your Stack Trace. Here's the short version.

Both throw; and throw ex; rethrow an exception from a catch block, but they leave very different evidence behind. throw; keeps the original stack trace. throw ex; resets it to the line in the catch block, so the log points at your error handler instead of the code that actually failed.

The difference in one sentence. throw; rethrows the exception currently being handled and keeps its stack trace intact. throw ex; throws the same exception… The exception type and message are identical either way.

Here's an example: The trace now starts in ProcessOrder, not in the repository call that failed.

When you want to add context: wrap, don't reset. If the caller needs a more meaningful exception, throw a new one and pass the original as the inner exception. The inner exception keeps its full stack trace, and your new exception adds the business context.

Rethrowing later: ExceptionDispatchInfo. Sometimes you capture an exception in one place and rethrow it somewhere else.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos