C# - Multiple Catch Blocks in Exception Handling Example

Learn about the multiple catch blocks in exception handling and demonstrating the example of multiple catch blocks in exception handling in C#. By Nidhi Last updated : April 03, 2023

Handling Multiple Catch Blocks

Here, we are demonstrating the multiple "catch" blocks., The program may generate a different kind of exceptions according to the input values of variables, and then we handle the exceptions using the "catch" block.

C# program to demonstrate the multiple catch blocks in exception handling

The source code to demonstrate multiple catch blocks is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the multiple catch blocks

using System;

class ExceptionDemo
{
    static void Main(string[] args)
    {
        int num1=0;
        int num2=0;
        int num3=0;
        
        try
        {
            Console.Write("Enter the value of num1: "); 
            num1 = int.Parse(Console.ReadLine());

            Console.Write("Enter the value of num2: ");
            num2 = int.Parse(Console.ReadLine());

            num3 = num1 / num2;

            Console.WriteLine("Num3 : " + num3);
        }
        catch (DivideByZeroException exp)
        {
            Console.WriteLine(exp.Message);
        }
        catch (FormatException)
        {
            Console.WriteLine("Exception: Invalid format");
        }
        catch (Exception)
        {
            Console.WriteLine("Other exception generated");
        }
    }
}

Output

Enter the value of num1: 10
Enter the value of num2: f
Exception: Invalid format
Press any key to continue . . .

Explanation

In the above program, we created a class ExceptionDemo that contains the Main() method. In the Main() method, we created three variables num1, num2, and num3 initialized with 0.

Here we input the character and then tried to covert it using Parse() method into integer then FormatException gets generated and print "Exception: invalid format" on the console screen.

C# Exception Handling Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.