C#: Throw, Throw, Throw

It’s nice to be back here after a long hiatus due to project deadlines, non-stop coding and lots of caffeine intake. For today’s session, I would like to share a simple but helpful technique involving the different throw implementations for Try Catch statement. This technique helped me a lot especially when debugging an application or logging the errors encountered by an application.

So, what is the difference with the Throw statement, Throw ex statement and Throw new Exception ? In order for us to clearly grasp the concept let us take a look at the sample program below:

MainProgramStackTrace

It’s just a simple console app with the Main method containing the try catch statement. Our goal here is to generate an exception called DivideByZeroException which will be handled by the try catch statement in three different ways with regards to the stack trace.

Stack Trace

CallStack

What is a Stack Trace? A Stack Trace is just a structured reporting a sequence of calls in the order that they have occurred. It means that if you have many methods inside calling other methods, the information about them will be stored in the stack trace and can be easily debugged.

Throw statement

The throw statement used in the try catch will preserve the original stack trace of the program. As you can see in the screenshot below, the stack trace contains the method where the exception happened. The decimal.Divide() method which generated the exception was displayed in the stack trace together with the Method GenerateException() which contains the decimal.Divide() method.

Throw

Throw with parameter statement

The throw with parameter statement is used when you don’t want to preserve the original stack trace of the program. It will just show the details of the encompassing method that generated the exception. So, in the sample stack trace below it just showed the GenerateException() method which contains the decimal.Divide() method that generated the exception.

ThrowEx

Throw new exception with parameter

The throw new exception with parameter does not only preserve the original stack trace but is also capable of creating your own custom exception message. The sample stack trace shows not only the decimal.Divide() method which actually generated the exception but also displays the custom exception message.

ThrowExNew

Summary

So there you have it, the different implementations of the throw statement. Just a short recap, we use the throw statement if you want to preserve the original stack trace, throw ex if you do not need the original stack trace and lastly, throw new exception if you want to preserve the original stack trace plus use a custom exception message.

Happy Coding 🙂

Leave a comment