Throwing exception in C#

      1 Comment on Throwing exception in C#

In C# there are 3 of ways to throw 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 NotImpletentedException.


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 in 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 different. Exception message is still preserved, but we lost the trace to source. Instead we have line number where we throw exc. I can barely imagine 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 🙂

Follow me:

One thought on “Throwing exception in C#

  1. Mikalojus

    Thanks, great post! Simple, yet something that I did not figure to find out myself. After reading the post I’ve changed exception rethrowing in the entire project.


Leave a Reply

Your email address will not be published. Required fields are marked *