Catching Exceptions in C#

An exception is an erroneous situation that occurs during program execution. Exceptional situation arise when an operation cannot be completed normally. When an exception occurs in an application, the system throws an error. The error is handled through the process of exception handling.
C# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control.
Exception handling is a way to handle errors at runtime that cause application termination.
.NET supports structured exception handling with the help of try, catch, finally and throw keywords.
C# provides following keywords to handle an exception. 
  • Try
  • Catch
  • Finally

The try block

The code, which seems to generate an exception, is placed under the try block. When an exception occurs in the try section, code compilation is transferred to the catch section.
  1. try  
  2. {  
  3.     //Code that may cause an exception  
  4. }  
A try block should have at least one catch or finally block. We can use both catch and finally block after the try block.
Remember there should be no other code between these blocks.
In the above code if no errors or errors are found, the flow of execution goes to the third block finally. If an exception is thrown execution goes to a catch block.
Exception Nesting
You can create an exception inside of another. This is referred to as nesting an exception.
To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es) clause.

The catch block

In this block you implement methods for dealing with any possible errors of the try block. At the end of this block execution continues to the last code block.
When an exception occurs in the try section, code compilation is transferred to the catch block.
  1. try  
  2. {  
  3. //Code that may cause an exception  
  4. }  
  5. catch (...)  
  6. {  
  7. //Code for handling errors  
  8. }  
The catch block should be immediately placed after try block.
The following program shows the catch block:
  1. using System;  
  2. namespace exception_example1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             try  
  9.             {  
  10.                 int i, k = 0, j;  
  11.                 Console.Write("Enter a number one: ");  
  12.                 i = Convert.ToInt32(Console.ReadLine());  
  13.                 Console.Write("Enter a number two: ");  
  14.                 j = Convert.ToInt32(Console.ReadLine());  
  15.                 k = i / j;  
  16.                 Console.WriteLine("Output of division : {0}", k);  
  17.                 Console.ReadKey();  
  18.             }  
  19.             catch (DivideByZeroException ex)  
  20.             {  
  21.                 Console.WriteLine(ex.Message);  
  22.                 Console.ReadKey();  
  23.             }  
  24.         }  
  25.     }  
  26. }  
In the above program if you input the second number as zero (0) it will generate DivideByZeroException.
The catch statement of the catch block takes an object of the exception class as a parameter, which refers to the raised exception. When the exception is caught, the statements within the catch blocks are executed.
One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then access this Exception.Message property to display an error message if you want.
You can have multiple catch blocks after the try block. See the code below:
  1. using System;  
  2. namespace exceptionHandling_example3  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             double Operand1, Operand2;  
  9.             double Result = 0.00;  
  10.             char Operator;  
  11.             Console.WriteLine("This program allows you to perform an operation on two numbers");  
  12.             try  
  13.             {  
  14.                 Console.Write("Enter a number: ");  
  15.                 Operand1 = double.Parse(Console.ReadLine());  
  16.                 Console.Write("Enter an operator: ");  
  17.                 Operator = char.Parse(Console.ReadLine());  
  18.                 Console.Write("Enter a number: ");  
  19.                 Operand2 = double.Parse(Console.ReadLine());  
  20.                 if (Operator != '+' &&  
  21.                     Operator != '-' &&  
  22.                     Operator != '*' &&  
  23.                     Operator != '/')  
  24.                     throw new Exception(Operator.ToString());  
  25.                 if (Operator == '/'if (Operand2 == 0)  
  26.                         throw new DivideByZeroException("Division by zero is not allowed");  
  27.                 switch (Operator)  
  28.                 {  
  29.                     case '+':  
  30.                         Result = Operand1 + Operand2;  
  31.                         break;  
  32.                     case '-':  
  33.                         Result = Operand1 - Operand2;  
  34.                         break;  
  35.                     case '*':  
  36.                         Result = Operand1 * Operand2;  
  37.                         break;  
  38.                     case '/':  
  39.                         Result = Operand1 / Operand2;  
  40.                         break;  
  41.                     default:  
  42.                         Console.WriteLine("Bad Operation");  
  43.                         break;  
  44.                 }  
  45.                 Console.WriteLine("\n{0} {1} {2} = {3}", Operand1, Operator, Operand2, Result);  
  46.             }  
  47.             catch (DivideByZeroException ex)  
  48.             {  
  49.                 Console.WriteLine(ex.Message);  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);  
  54.             }  
  55.             Console.ReadKey();  
  56.         }  
  57.     }  
  58. }  

The finally block

The finally block is executed whether or not an exception was thrown.
  1. try  
  2. {  
  3. //Code that may cause an exception  
  4. }  
  5. catch (...)  
  6. {  
  7. //Code for handling exception  
  8. }  
  9. finally  
  10. {  
  11. //clean up code  
  12. }  
The catch block is used to handle exceptions that occur in a try block. The finally block is used to guarantee the execution of statements, regardless of whether an exception has occurred or not.
See the code to understand finally block
  1. using System;  
  2. namespace exception_example1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int i, k = 0, j;  
  9.             try  
  10.             {  
  11.                 Console.Write("Enter a number one: ");  
  12.                 i = Convert.ToInt32(Console.ReadLine());  
  13.                 Console.Write("Enter a number two: ");  
  14.                 j = Convert.ToInt32(Console.ReadLine());  
  15.                 k = i / j;  
  16.             }  
  17.             catch (DivideByZeroException ex)  
  18.             {  
  19.                 Console.WriteLine(ex.Message);  
  20.                 Console.ReadKey();  
  21.             }  
  22.             finally  
  23.             {  
  24.                 Console.WriteLine("Output of division : {0}", k);  
  25.                 Console.ReadKey();  
  26.             }  
  27.         }  
  28.     }  
  29. }  
Points about finally block 
  • You can have only one finally block for each try block.
  • It is not mandatory to have a finally block after a try block.
  • The finally block is used to do all the clean up code.
  • It does not support the error message, but all the code contained in the finally block is executed after the exception is raised.
To cover unmanaged resource we use finally block. For example when we are not able to find file/database exception we close the file.
It is used for cleaning up resources that your program might have used and generic code that should always be executed.

Exceptions and Custom Messages

Sometimes, the message provided by the Exception class may not be clear to the normal users. As an alternative, you can create your own message and display it to the user.
You can display the exception message along with the user defined custom message. See the program below.
  1. using System;  
  2. namespace exceptionHandeling_Example2  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int num1, num2, sum;  
  9.             try  
  10.             {  
  11.                 Console.Write("Enter first number : ");  
  12.                 num1 = int.Parse(Console.ReadLine());  
  13.                 Console.Write("Enter second number : ");  
  14.                 num2 = int.Parse(Console.ReadLine());  
  15.                 sum = num1 + num2;  
  16.                 Console.WriteLine(sum);  
  17.             }  
  18.             catch (Exception e)  
  19.             {  
  20.                 Console.WriteLine(e.Message);  
  21.                 Console.WriteLine("The error indicates that the input was not provided" +  
  22.                 "in the desired format, You might have provide input not as integer");  
  23.             }  
  24.             Console.ReadKey();  
  25.         }  
  26.     }  
  27. }  

Throwing an Exception

Exceptions can be explicitly generated by a program using the throw keyword.
Exceptions are used to indicate that an error has occurred while running the program. Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.
  1. using System;  
  2. namespace exceptionHandling_example4  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int total = 0;  
  9.             int[] arr = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
  10.             try  
  11.             {  
  12.                 for (int i = 0; i <= 10; i++)  
  13.                 {  
  14.                     total += arr[i];  
  15.                 }  
  16.                 throw new System.Exception();  
  17.             }  
  18.                 catch(Exception ex)  
  19.                 {  
  20.                     Console.WriteLine("Unknown error");  
  21.                     Console.ReadLine();  
  22.                 }  
  23.         }  
  24.     }  
  25. }  
We should not throw exception as it is not good practice of programing. We should try to handle it in a more better manner.
I will be explaining more about exception handling and how to throw exception in my coming articles.

The Exception Class

To support exception handling, the .NET Framework provides a special class called Exception. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take an appropriate action.
Normally, Exception mostly serves as the general class of exceptions. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier.
As a result, almost any type of exception you may encounter already has a class created to deal with it. Therefore, when your program faces an exception, you can easily identify the type of error.
Exceptions are of two types:  
  • SystemException
  • ApplicationException
There are many exception classes, which are directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are System.System.Exception and System.ApplicationException.
The Hierarchy of Exception Class 
SystemException: These exceptions are defined and the common language runtime throws SystemException. The System.System.Exception acts as a base class for all predefined exception.
ApplicationException:  These exceptions are not defined. The ApplicationException is thrown by a user program rather than the runtime. They are non-fatal error. If any user-defined application requires its own exception, it should inherit the exception from the System.ApplicationException class.
Following are some common exception classes.
Exception ClassCauses
SystemExceptionA failed run-time checks; used as a base class for other.
AccessExceptionFailure to access a type member, such as a method or field.
ArgumentExceptionAn argument to a method was invalid.
ArgumentNullExceptionA null argument was passed to a method that doesn't accept it.
ArgumentOutOfRangeExceptionArgument value is out of range.
ArithmeticExceptionArithmetic over - or underflow has occurred.
ArrayTypeMismatchExceptionAttempt to store the wrong type of object in an array.
BadImageFormatExceptionImage is in the wrong format.
CoreExceptionBase class for exceptions thrown by the runtime.
DivideByZeroExceptionAn attempt was made to divide by zero.
FormatExceptionThe format of an argument is wrong.
IndexOutOfRangeExceptionAn array index is out of bounds.
InvalidCastExpressionAn attempt was made to cast to an invalid class.
InvalidOperationExceptionA method was called at an invalid time.
MissingMemberExceptionAn invalid version of a DLL was accessed.
NotFiniteNumberExceptionA number is not valid.
NotSupportedExceptionIndicates that a class does not implement a method.
NullReferenceExceptionAttempt to use an unassigned reference.
OutOfMemoryExceptionNot enough memory to continue execution.
StackOverflowExceptionA stack has overflown.


By now, you should have a good understanding of exception handling and their usage. Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this article.