Exception Handling in C#

Exception Handling in C#

Last Updated on September 17, 2017 by Aram

Exception handling is a very important topic that is sometimes not properly understood or less used.

In this article, I will explain to you about the Exceptions, and how to handle them in C#. I will clarify the different keywords that represent the exception handling in C#. and I will provide some code samples to further illustrate the different uses of those keywords.

So have you seen the below message?

Object reference not set to an instance of an object. 

For sure you have met this message before, right?

The aforementioned message is the textual representation for the predefined exception of type NullReferenceException

This message means that something went wrong with the execution within one of your lines of code, particularly it means that you are trying to access a member, property or method of an object that has a null reference, this is called Exception.

What is an Exception?

An Exception is an error, a fault, a problem or a false situation in your program, where it can change the flow of execution, to a different part of the program dismissing any remaining code within the current executing method or terminating the execution.

Now to avoid letting your program execution get diverged from its actual flow of process, you need a way to process this Exception by doing Exception Handling.

In C#, Exceptions are classes that are defined under the Namespace System.Exception

There is a long list of predefined exceptions within the .Net Framework, these include:

IndexOutOfRangeException , InvalidOperationException, ArgumentOutOfRangeException

You can check msdn’s System Exception definition to see all the predefined exception classes inheriting from System.Exception Class

You can also define your own exception class by inheriting from the base System.Exception class

How is Exception Handling done?

Exception handling is done by implementing the keywords try catch , and optionally you can use the keyword finally , after the last catch block, also you can use the keyword throw  to raise an exception manually or re-throw an exception from within a catch block.

try catch keywords are code blocks. When you put a code in try block, you are making that code safe, since you are verifying it, and will catch the error that will be raised, based on what types you defined in your catch blocks.

Whenever there is an error raised in one of the lines of the try block, the CLR will check the catch part of the block, and will determine if Exception type defined in the catch statement is either of the same type of the Exception or is of a base class of the Exception that is being raised. Then It will execution the code within the matching catch block.

You can add as many catch blocks as needed, but keeping in mind that the order of catch blocks must be starting with the most specific or derived match of the expected exception until you reach the lease specific or most generic match, or the System.Exception class.

Sometimes you might need to execute a cleanup or a conclusive code whether the code in your try block raises an error or not. This can be achieved the implementing the keyword finally. This finally block will be executed regardless of what the try block resulted.

Another useful keyword in the Exception Handling in C#, is throw. This can be used to trigger or raise an exception of any type, whenever needed.

This is mainly used for 2 purposes:

  • Trigger an exception manually. Sometimes you might need to raise a new exception after doing some if statement, or let’s say you have an unimplemented method and you want to deny anyone not to use it, then you can write

  • Re-throw an exception from inside a catch block. In some cases you might want to catch an exception, log it and then re-throw it back to the caller. It should be done this way:

Or by passing the full exception object to the inner exception parameter of the Exception constructor. See Below:

The thrown exception will be propagated up to the caller of the method.

The throw keyword is usually used whenever you prefer not to handle some exception within a given method, and keep the handling of the exception to the caller method or a different. This way you will propagate the exception stack trace to another part of the application.

You should always keep in mind that catching exception without doing anything to it (empty catch block), will lead to swallowing the exception without you knowing about it. Which means that you will be disguised that your code is functioning normal, while it is generating an exception and going unnoticed.

For further reading about Exception handling in programming languages, check Wikipedia’s exception handling page.

Examples

Now let’s see some code examples to better showcase the exception handling in C#

The below is an exercise that currently, when run, will throw a DivideByZeroException.

You should add the proper exception handling code so that the testing assertion can pass.


The below is an example of using multiple catch blocks, in File reading program, where this will showcase how you should include the catch blocks from the most to least specific exceptions that might occur.

Note that we could have used finally block to dispose the Stream and StreamReader Objects, however, since we know that Stream and StreamReader classes both implement the IDisposable Interface, then the cleaner and much better way to do through the using keyword. Even if there is an exception raised from any of the above objects, the using keyword will dispose the opened stream object and the stream reader object.

 

Now in the below sample we include the keyword throw to raise a new exception of type MethodNotImplementedException, this exception is a custom created one, it inherits from the InvalidOperationException


InvalidOperationException is usually used when there is a method that has actually implementation yet, so in order to avoid anyone using it, we make it raise this kind of exception.

However, in this sample we are raising a custom exception just to showcase how you can create your own exception class and use it in your project.


Always make sure to suffix your custom exception class with the word Exception

 

Conclusion

Always make sure to properly handle exceptions in your C# code, whenever you sense a code block that might generate an error, due to any reason. When handling exceptions, add the catch block beginning with the most specific exception that you think it will occur, then go less specific until most generic. Avoid catching exceptions without taking the needed actions and follow the practice of logging all your exceptions.

Leave a Reply