Skip to content
Related Articles

Related Articles

Improve Article

Exception Handling in C#

  • Last Updated : 15 Sep, 2021
Geek Week

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.
 

KeywordDefinition
tryUsed to define a try block. This block holds the code that may throw an exception.
catchUsed to define a catch block. This block catches the exception thrown by the try block.
finallyUsed to define the finally block. This block holds the default code.
throwUsed to throw an exception manually.

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

csharp




// C# program to show how
// Exceptions occur in a program
using System;
 
class GFG {
 
    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
    }
}

Runtime 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 
 

Output:
 



1
2
3
4
5

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
}

 

csharp




// Exception handling of above code
// using try catch blocks
 
using System;
 
class Program : System.Exception {
    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 {
 
            // Try to access invalid index of array
            Console.WriteLine(arr[7]);
            // An exception is thrown upon executing
            // the above line
        }
        catch (IndexOutOfRangeException e) {
 
            // The Message property of the object
            // of type IndexOutOfRangeException
            // is used to display the type of exception
            // that has occurred to the user.
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }
    }
}

Output:
 

1
2
3
4
5
An Exception has occurred : Index was outside the bounds of the array.

 

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.
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
}

 

csharp




// C# Program to show use of
// multiple try catch blocks
using System;
 
class Program {
 
    static void Main(string[] args)
    {
        int[] arr = {19, 0, 75, 52};
 
        try {
 
            // Try to generate an exception
            for (int i = 0; i < arr.Length; i++) {
                Console.WriteLine(arr[i] / arr[i + 1]);
            }
        }
 
        // Catch block for invalid array access
        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
        // Will execute irrespective of the above catch blocks
        finally {
            for (int i = 0; i < arr.Length; i++) {
                Console.Write(" {0}", arr[i]);
            }
        }
    }
}

Output: 
 

An Exception has occurred : Attempted to divide by zero.
 19 0 75 52

 

User Defined Exceptions

User-defined exceptions are useful when we want to code an exception that may not be defined by the language. For example, in a boiler room, if the temperature rises above some threshold then the heat must be turned off. For understanding how user-defined exceptions are used we take an example of a division by zero. Here we define a class DivByZero that inherits from Exception and is called by the DivisionOperation function when the denominator is equal to zero. Since the call for the function is may or may not throw an exception it is placed in the try block. A catch block is defined to catch any exception of type Exception and the Message property prints the type of exception that has occurred.
 

csharp




// C# program to show the user defined exceptions
using System;
 
// User defined Exception class
// Child of Exception
class DivByZero : Exception {
 
    // Constructor
    public DivByZero()
    {
        Console.Write("Exception has occurred : ");
    }
}
 
class Program {
 
    // Method to perform Division
    public double DivisionOperation(double numerator,
                                 double denominator)
    {
        // throw exception when denominator
        // value is 0
        if (denominator == 0)
            throw new DivByZero();
 
        // Otherwise return the result of the division
        return numerator / denominator;
    }
 
    // Main
    static void Main(string[] args)
    {
        Program obj = new Program();
        double num = 9, den = 0, quotient;
        try {
            // Code block that may cause an exception
            quotient = obj.DivisionOperation(num, den);
            Console.WriteLine("Quotient = {0}", quotient);
        }
        // Catch block to catch the generic exception
        catch (Exception e) {
            // Message property of exception object e
            // will give the specific type of the exception
            Console.Write(e.Message);
        }
    }
}

Output: 
 

Exception has occurred : Exception of type 'DivByZero' was thrown.

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :