“throw” vs “throw ex” vs “throw new” in .NET/C#

It is a standard practice to wrap code that can potentially fail in try/catch blocks to allow for applications either to identify or recover from exception scenarios.

A common strategy is to log the exception message to document the failure scenario and then rethrow the exception for the higher layers to act accordingly. This strategy of catching an exception, processing (logging in this scenario) and then rethrowing so that the caller can do its own processing is called Exception bubbling.

If you happened to work on enough codebases one would notice the throw statements in the catch block to be a mix of “throw’, “throw ex” and “throw new”. Most of the times the usages are a result of the developer not understanding the nuances of the usage and which g

  1. throw – rethrows the original exception and preserves the original stack trace.
  2. throw ex – throws the original exception but resets the stack trace, destroying all stack trace information until the catch block.
  3. throw new Exception (with InnerException) – throws an new Exception overwriting the message and including the original exception as an InnerException.
  4. throw new Exception (without InnerException) – A variation of the new Exception is one without the InnerException where all information of the original exception is lost. This is typically used for untrusted clients we want to hide information.