Throwing Exception In C#

Published on 20 April 2017

In C# there are 3 of ways to throw an exception.

  • throw
  • throw ex
  • throw new Exception("message", innerException)

Our sample:

I will make changes in line 30 (purple box) and catch exception in parent method in simple try catch(Exceptiop e) block. Method throwing actual exception is called ThrowExceptionMethod() and is not shown here for simplicity. ThrowExceptionMethod() throw NotImplementedException.

throw

throw is the most common, shortest and preferred way to throw exceptions in C#.As we can observe exception Message is set to "The method or operation is not implemented". The stack trace contain ThrowExceptionMethod() and this is excellent because the origin of the error preserved.

This is the preferred way of throwing exception in C#

throw exc

throw exc is behaving differently. The exception message is still preserved, but we lost the trace to the source. Instead, we have line number where we throw exc. I can barely imagine a situation where this is useful. Maybe if we want to hide the original exception place. This could be useful if we don't want to expose implementation details in code.

throw new Exception

throw new Exception() is widely used when we need to pack inner exception in our custom exception type. Otherwise throw should be used. Here we also have stack trace (inside inner exception).

Quality - where are you!!!

FxCop has rule CA2200: Rethrow to preserve stack details that can be set so we can ensure all developers will rethrow :)

comments powered by Disqus