How do you handle an exception thrown in C# – Programming, Pseudocode Example, C# Programming Example
C# C# Console

How do you handle an exception thrown in C#

We generally use exception and stack trace for tracking down to the problem in our code. But a lots of the time, in case you are not using proper way to throw exceptions then it might make difficult to narrow down the problem. Whenever we throw an exception; it is recorded into the exception stack trace.

Let understand this with an example. Consider the below console application:

You may see the that the initially the FirstCall() method is called which internally calling SecondCall() > ThirdCall() > ForthCall() and the ForthCall is generating System.DivideByZeroException exception. Each function is throwing the exception by using throw keyword. Output of the above program will be:

By looking at above stack trace you could easily track down the root cause of the problem. Method ForthCall() is the culprit.

Do not Throw Same Exception

A lots of time its common mistake to throw same exception again instead of re-throwing it. Look at below bad practice of coding:

“throw ex;” is basically throwing the same exception again instead of re-throwing the original exception. Because of this the all exception stack trace information is lost till this point and stack started to build again. The output of above program will be:

You can see we can only see methods SecondCall() and FirstCall() in the exception stack. Final conclusion of this whole article is to be careful while throwing exception.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.