10X Sale
kh logo
All Courses
  1. Tutorials
  2. Programming Tutorials

Exception Handling in C#

Updated on Sep 3, 2025
 
45,995 Views

handling is used to detect and handle these runtime errors. If there is no exception handling mechanism created by the programmer, then the default mechanism is used by the runtime environment. This terminates the program execution.

Exception Handling Keywords

The exception handling mechanism uses three main keywords i.e. try, catch and finally. Details about these are given as follows:

1. try

If the exception occurs inside the try block, the control is transferred to the required catch block. There may be multiple catch blocks after the try block.

2. catch

The catch block handles the exception that has occurred in an appropriate manner using exception handling mechanisms.

3. finally

The finally block executes some statements irrespective of whether an exception has occurred or not. If there is no exception in the try block, then control directly transfers to finally block and skips the catch block.

The syntax of the try, catch and finally keywords in exception handling is given as follows:

try
{
    // Statements that cause exception
}
catch (ExceptionType EName)
{
    // Statements that handle exception
}
finally
{
     // Remaining statements to be executed
}

In the above syntax, the try block contains the exceptions that may occur. There can be multiple catch blocks that handle the required exceptions. The finally block executes some remaining statements.

A program that demonstrates exception handling is given as follows:

using System;
namespace ErrorHandlingDemo
{
  class Example
  {
     static void Main(string[] args)
     {
         int result = 0;
         int a = 25;
         int b = 0;
         try
        {
           result = a / b;
        }
        catch (DivideByZeroException)
        {
           Console.WriteLine("Exception occured");
        }
        finally
        {
           Console.WriteLine("Result: {0}", result);
        }
     }
  }
}

Source Code: Program that demonstrates exception handling in C#

The output of the above program is as follows:

Exception occured
Result: 0

Now let us understand the above program.

The try block stores the result of a/b. If b is 0, then there is a DivideByZeroException and control goes to the catch block. In the catch block, it is printed that an exception has occurred. The finally block is executed if there is an exception or not. It prints the result of a/b. The code snippet for this is as follows:

int result = 0;
         int a = 25;
         int b = 0;
         try
        {
           result = a / b;
        }
        catch (DivideByZeroException)
        {
           Console.WriteLine("Exception occured");
        }
        finally
        {
           Console.WriteLine("Result: {0}", result);
        }

User Defined Exceptions

User defined exceptions are custom exceptions that can be created by the users. This is done by inheriting the exception class.

A program that demonstrates user defined exceptions is given as follows:

using System;
namespace UserDefinedExceptionDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        Age a = new Age();
        try
        {
           a.displayAge();
        }
        catch(AgeIsNegativeException e)
        {
           Console.WriteLine("AgeIsNegativeException: {0}", e.Message);
        }
     }
  }
}
public class AgeIsNegativeException: Exception
{
  public AgeIsNegativeException(string message): base(message)
  {
  }
}
public class Age
{
  int age = -5;
  public void displayAge()
  {
     if(age < 0)
     {
        throw (new AgeIsNegativeException("Age cannot be negative"));
     }
     else
     {
        Console.WriteLine("Age is: {0}", age);
     }
  }
}

Source Code: Program that demonstrates user defined exceptions in C#

The output of the above program is as follows:

AgeIsNegativeException: Age cannot be negative

Now let us understand the above program.

The try and catch blocks are available in the Main() function. The displayAge() function is called in the try block. If the age is less than zero, then an exception message is printed in the catch block because the age cannot be less than zero. The code snippet for this is as follows:

 static void Main(string[] args)
     {
        Age a = new Age();
        try
        {
           a.displayAge();
        }
        catch(AgeIsNegativeException e)
        {
           Console.WriteLine("AgeIsNegativeException: {0}", e.Message);
        }
     }

The variable of type int is declared in class Age. The function displayAge() throws an exception if the age is less than zero. Otherwise, it prints the age. The code snippet for this is as follows:

public class Age
{
  int age = -5;
  public void displayAge()
  {
     if(age < 0)
     {
        throw (new AgeIsNegativeException("Age cannot be negative"));
     }
     else
     {
        Console.WriteLine("Age is: {0}", age);
     }
  }
}
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses