Exception Handling in C#

AramT
1,551 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Next: Examples

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 custom 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 execute 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. The 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 throw new InvalidOperationException();

  • 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:

try
{
    // Some code to verify for exceptions
}
catch {
    throw;
}

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

try
{
    // Some code to verify for exceptions
}
catch (Exception ex)
{
    throw new Exception("Custom Message", ex);
}

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.

Do not put your code inside a try catch block if you are not willing to do anything with the exception caught.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content