Exception Handling Mechanism In C#


  • .NET provides a structured way of handling the runtime errors. Business logic and error handling code is separate.
  • The errors that occur during the execution of a program are called the runtime errors or the exceptions.

For example

  • Division by 0.
  • Stack overflow.
  • Invalid type casting.
  • File not found.

Object-Oriented way of error handling is

  1. Classes to handle different types of errors.
  2. FileNotFoundException class to represent, if the file not found.
  3. IOException class to represent, if the file is already open.
  4. SecurityException class to represent, if the caller does not have permission to access the file.
  5. Easy to program and extend

Runtime errors occur during the execution of a program. Some exceptions are given below.

  • Division by 0 exception occurs, when the denominator is zero.
  • Stack overflow exception occurs, when there is no memory available to allocate on stack.
  • File not found exception can occur, when we try to access a file from a particular location, where it does not exit.

These exceptions abnormally terminate a program. To avoid this, C# provides an in-built feature that is called an exception handling mechanism.

Exception handling mechanism provides a way to respond to the run time errors in the program by transferring control to special code called handler. This feature allows a clean separation between error detection code or business logic and error handling code.

The exception handling mechanism in C# provides try and catch blocks to effectively handle it.

Let's see how to handle an exception practically.

  1. For this, create new C# console project, as shown below.

  2. Let's write a code for reading a text file for the specific path, as shown below.
  • The file path is shown below.

  • Now, let’s try to read this sample file, using C# code, as given below.
    1. using System;  
    2. using System.IO;  
    3. namespace ConsoleApplication1 {  
    4.     class Program {  
    5.         static void Main(string[] args) {  
    6.             StreamReader strmRdr = new StreamReader(@ "E:\Exception Handling\sample.txt");  
    7.             Console.WriteLine(strmRdr.ReadToEnd()); //Read the file to the end  
    8.             strmRdr.Close(); //after reading close the file  
    9.             Console.ReadLine();  
    10.         }  
    11.     }  
    12. }  

  1. Let's implement one exception to this reading code. Let’s change the file name so that in the file path, we can make it not exist and change the code, as shown below, and see what happens.

    As you see here, you will be getting an Exception System.IO.FileNotFoundException.
  1. Now, we will see how to handle this. Using try catch, rewrite the code, as shown below.
    1. try {  
    2.     StreamReader strmRdr = new StreamReader(@ "E:\Exception Handling\sample1.txt");  
    3.     Console.WriteLine(strmRdr.ReadToEnd()); //Read the file to the end  
    4.     strmRdr.Close(); //after reading close the file  
    5.     Console.ReadLine();  
    6. catch (Exception ex) {  
    7.     Console.WriteLine(ex.Message);  
    8. }   

    Here, we will get the exact exception and the application will not crash.

    It is not a good way because here, we are displaying all the error messages which sometimes the user can’t understand. The hackers may use this information hack.

    Thus, we need to hide all these things and we have to display an error message in a better way. Exception is actually a class, which is derived from System.Exception class. This class has several useful properties, which provide valuable information about the exception.

    There are two main methods in this exception.

    Gets message that describes the current exception.

    Stack Trace
    Provides the call stack to the line number in the method, where the exception occurred

  1. For this exception, we can use FileNotFoundException in catch block, so whenever this exception gets this, catch block will execute , else it does not, as shown below.

    See above that whenever we get FileNotFoundException, we can give the user a defined messge. Let’s check if an exception is something else other than this, then it will happen.

    I have changed the directory name, which does not exist, so the new exception is there. Since I am handling only FileNotFound exception, we have to give DirectoryNot found exception; you have to show some message and block this error.

  1. Now, we have to know how to handle these exceptions but it still has a problem; i.e., I am getting an error in the line.
    1. StreamReader strmRdr = new StreamReader(@"C:\Exception Handling\sample1.txt");  

    Whatever is there will not execute. After getting an error, it goes to catch block, then this stream reader is still open. We need to release this resource for which we have to write final block after catch blocks. Actually, it is a good practice to write final block after catch block, if we are using resources like stramreader conection open etc., as shown below. 

    1. using System;  
    2. using System.IO;  
    3. namespace ConsoleApplication1 {  
    4.     class Program {  
    5.         static void Main(string[] args) {  
    6.             StreamReader strmRdr = null;  
    7.             try {  
    8.                 strmRdr = new StreamReader(@ "C:\Exception Handling\sample.txt");  
    9.                 Console.WriteLine(strmRdr.ReadToEnd()); //Read the file to the end  
    10.                 strmRdr.Close(); //after reading close the file  
    11.                 Console.ReadLine();  
    12.             } catch (FileNotFoundException fx) {  
    13.                 Console.WriteLine("Please check your file Name");  
    14.                 Console.ReadLine();  
    15.             } catch (DirectoryNotFoundException fx) {  
    16.                 Console.WriteLine("Please give a path where file exactly locate");  
    17.                 Console.ReadLine();  
    18.             } finally {  
    19.                 if (strmRdr != null) {  
    20.                     strmRdr.Close();  
    21.                 }  
    22.             }  
    23.         }  
    24.     }   

    The Finally block will execute every time, so make sure whatever code is there inside the finally block is perfect.

  1. If you get an exception inside the finally block it looks like this.

As you can see the file path is correct, even though the finally block is executed. I got an error conversion failed exception. Thus, what to do in these situations?

We can handle this in higher levels, as shown below, by adding try catch for all these codes

Other .NET exception classes are given below.

  • SystemException
  • FornatException
  • ArithmaticException
  • CoreException
  • ArgumentException
  • OutOfMemoryException
  • NullReferenceException
  • InvalidOperationException
  • FormatException
  • ArrayTypeMismatchException
  • NotSupportedException, etc.


  • Exception class is the base class for all the exceptions
  • Any code that is written cannot be completely bug-free.
  • It is the responsibility of the developer to see to it that there are minimum bugs in the code.

Similar Articles