Table of contents
1.
Introduction
1.1.
Syntax
1.2.
Keywords in exception handling in C#
1.3.
Examples of Try Catch and Finally blocks used in exception handling in C#
1.4.
Exception classes and their description in C#
2.
FAQs
3.
Key Takeaways
Last Updated: Mar 27, 2024

Exception Handling in C#

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will learn about exception handling in C#. But, Before we start learning exception handling, let’s learn about exceptions.

A problem that occurs during the execution of a program is referred to as an exception. A C# exception is a response to a rare event that occurs during the execution of a program, such as trying to divide by zero.

Exceptions allow control to be passed from one part of the program to another. Exceptions must be handled to prevent the crashing of the program. The handling of exceptions is known as exception handling. There are try, catch & finally blocks for exception handling in C#.

Recommended Topic, Palindrome in C#, singleton design pattern in c# and  Ienumerable vs Iqueryable

Syntax

If a block raises one, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around any code that could cause an exception to occur. The following is the syntax of try, catch, and finally blocks for exception handling in C#.

try

{

    //code to try block goes here

    // put the statements here that may raise exceptions

}

catch(SomeSpecificException E1)

{

    //statements to handle the exception goes here

}

finally

{

    // Statements to execute after the try (and possibly catch) blocks

    // final cleanup code

}

Note: A try block without a catch block or finally block will raise a compilation error.

Keywords in exception handling in C#

  • try: it is used to define a try block while handling exceptions. It holds the code that may throw an exception. It is followed by one or more catch blocks.
  • catch: it is used to define the catch block. It catches the exception thrown by try block.
  • finally: It is used to define the finally block. This block is used to execute a given set of statements, whether an exception is thrown or not thrown. The finally block is an optional block and should always come after a try or catch block.
  • throw: In C#, the throw keyword is used to throw an exception when a problem shows up. It is used to throw an exception manually.

Examples of Try Catch and Finally blocks used in exception handling in C#

The following example program will show how exception occurs in C#.

Code:

using System;
class CodingNinjas {
    static void Main(string[] args)
    {
        // Declaring an array of size 3 (i.e. max index is 2)
        int[] arr = {3, 2, 4};
  int size=arr.Length;
        // printing the values of the array
        for (int i = 0; i < size; i++) {
            Console.WriteLine(arr[i]);
        }
 
        // Try to access the invalid index of array
        Console.WriteLine(arr[5]);
        // The above statement will throw the exception
    }
}

Output:

The following example shows how to use try block with a single catch block for exception handling in C#.

Code:

using System;
class CodingNinjas {
    static void Main(string[] args)
    {
        int num = 0;
        int div = 0;
        try
        {   // try to divide 100 with 0 and store the result in div 
            div = 100 / num;
            Console.WriteLine("Try block");
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Exception occurred");
        }
        Console.WriteLine($"The result is {div}");
    }
}

Output:

Exception occurred

The result is 0

Now let’s learn how to use multiple try-catch blocks with finally block.

Using multiple try-catch blocks with finally block

The following examples show exception handling in C# using multiple try-catch blocks.

Code:

using System;
class CodingNinjas {
    static void Main(string[] args)
    {
        int[] arr = {5,4,0,10,3};
 
        try {
      int size=arr.Length;
            // Try to generate an exception by dividing the elements
            for (int i = 0; i < size; i++) {
                Console.WriteLine(arr[i] / arr[i + 1]);
            }
        }
        
        // Catch block for out of range exceptions
        catch (ArgumentOutOfRangeException e) {
 
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }
        
        // Catch block for divide by zero exception
        catch (DivideByZeroException e) {
 
            Console.WriteLine("An Exception has occurred : {0}", e.Message);
        }
 
        // Catch block for invalid array access
        catch (IndexOutOfRangeException e) {
 
            Console.WriteLine("An Exception has occurred: {0}", e.Message);
        }
 
        // Finally block will execute irrespective of the above catch blocks
        finally {
    int size=arr.Length;
            Console.WriteLine("finally block starts here");
            for (int i = 0; i < size; i++) {
                Console.Write(" {0}", arr[i]);
            }
        }
    }
}

Output:

1

An Exception has occurred: Attempted to divide by zero.

finally block starts here

 5 4 0 10 3

Exception classes and their description in C#

In C#, the exceptions are represented by classes. And the exception classes are mainly derived from System.Exception class in C#.

The following are some exception classes derived from System. Exception class with their short description.

Exception Class

Description 

System.IO.IOException

It handles Input/Output errors.

System.DivideByZeroException

It handles errors generated from dividing a dividend with zero.

System.NullReferenceException

It handles errors generated from referencing a null object.

System.InvalidCastException

Handles errors generated during typecasting.

System.StackOverflowException

Handles errors generated from stack overflow.

System.IndexOutOfRangeException

It handles errors generated when a method refers to an array index out of range.

System.ArrayTypeMismatchException

It handles errors generated when the type is mismatched with the array type.

System.OutOfMemoryException

Handles errors generated from insufficient free memory.

This concludes the exception handling in C#. Now let’s move on to the FAQ section.

FAQs

  1. What are exceptions?
    A problem that occurs during the execution of a program is referred to as an exception.
  2. Can we use try block without catch block for exception handling in C#?
    You can not use the 'try' block without the catch block. Try block without using the catch block program will give a compilation error.
  3. Can we use a try block nested in another try block?
    Yes, a try block can be nested in another try block.
  4. What does the throw keyword do?
    In C#, the throw keyword is used to throw an exception when a problem shows up. It is used to throw an exception manually.
  5. What is the difference between exceptions and errors?
    The exceptions are raised due to some internal event that obstructs the normal flow of the execution while the errors are the problems in the program due to which the program is not able to complete its execution.

Key Takeaways

This article extensively discussed the exception handling in C#. We learned the syntax of try, catch, and finally blocks with multiple examples. We learned some exception classes of C# language.

Refer here to know more about exception handling in other programming languages.

We hope that this blog has helped you enhance your knowledge regarding exception handling in C#, and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass