C# Exceptions

Exception Handling in C#

An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program.

In such a case, we create an exception object and call the exception handler code. The execution of an exception handler so that the program code does not crash is called exception handling. Exception handling is important because it gracefully handles an unwanted event, an exception so that the program code still makes sense to the user.

Keyword

Definition

try

Used to define a try block. This block holds the code that may throw an exception.

catch

Used to define a catch block. This block catches the exception thrown by the try block.

finally

Used to define the finally block. This block holds the default code.

throw

Used to throw an exception manually.

Let us take a simple example to understand what an exception is:

using System;

class Program
{
    static void Main(string[] args)
    {
        // Declare an array of max index 4
        int[] arr = { 1, 2, 3, 4, 5 };

        // Display values of array elements
        for (int i = 0; i < arr.Length; i++)
            Console.WriteLine(arr[i]);

        // Try to access invalid index of array
        Console.WriteLine(arr[7]);
        // An exception is thrown upon executing the above line
    }
}

Error

Unhandled Exception: 
System.IndexOutOfRangeException: Index was outside the bounds of the array. 
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array. 
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0 

In the code given above, the array named arr is defined for 5 elements, indices 0 to 4. When we try to access the 7th element of the array, that is non-existent, program code throws an exception and the above message is displayed.

The exception can be handled using the System.Exception class of C#. This will be depicted in the code given below.

Exception Handling Using try-catch block

The code given below shows how we can handle exceptions using the try-catch block. The code that may generate an exception is placed inside the try block. In this case, the access to the 7th element is put inside the try block.

When that statement is executed, an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException is used to display a message to the user about the exception that has occurred.

Syntax

try
{
  // statements that may cause an exception
}
catch(Exception obj)
{
  // handler code
}
using System;

class Program
{
    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };

        for (int i = 0; i < arr.Length; i++)
            Console.WriteLine(arr[i]);

        try
        {
            Console.WriteLine(arr[7]);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }
    }
}

Using Multiple try-catch blocks

In the code given below, we attempt to generate an exception in the try block and catch it in one of the multiple catch blocks. Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered.

The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not. In the program given below the elements of the array are displayed in the finally block.

The finally block is the part of the code that has to be executed always!

Syntax

try
{
  // statements that may cause an exception
}
catch(Specific_Exception_type obj)
{
  // handler code
}
catch(Specific_Exception_type obj)
{
  // handler code
}
.
.
.
finally
{
  //default code
}
using System;
class Program
{
    static void Main(string[] args)
    {
        int[] arr = { 19, 0, 75, 52 };

        try
        {
            for (int i = 0; i < arr.Length; i++)
                Console.WriteLine(arr[i] / arr[i + 1]);
        }

        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }

        // Catch block for attempt to divide by zero
        catch (DivideByZeroException e)
        {
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }

        // Catch block for value being out of range
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }

        // Finally block
        finally
        {
            Console.WriteLine("In finally block");
        }
    }
}

Last updated