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

Here, we are going to learn about the multiple catch blocks in exception handling and demonstrating the example of multiple catch blocks in exception handling in C#.
Submitted by Nidhi, on September 16, 2020

Here we demonstrate the multiple "catch" blocks, here 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.


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;
            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)
        catch (FormatException)
            Console.WriteLine("Exception: Invalid format");
        catch (Exception)
            Console.WriteLine("Other exception generated");


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


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!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.