Home » C#

C# exception handling with multiple catch blocks

Here, in this tutorial, we are going to learn about the exception handling with multiple catch blocks in C# with examples and discussing the various exceptions also.
Submitted by IncludeHelp, on September 20, 2019

In a C# program, we can use multiple catch blocks to handle the multiple exceptions, because sometimes it is also required to handle multiple exceptions of a coding section and obvious a coding section can generate multiple exceptions.

Consider the below example,

Here, we are using two catch blocks, one is using to catch "DivideByZeroException" which will occur when any number will be divided by zero and second is using to catch any other exceptions as we have discussed in previous tutorial (C# exception handling) that "Exception" class is a superclass and can be used to handle all type of exceptions.

using System;

class Program
{
    static void Main()
    {
        int number1 = 20;
        int number2 = 0;
        int result  = 0;

        try
        {
            result = number1 / number2;
            Console.WriteLine("Result : " + result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
        }
        catch (Exception)
        {
            Console.WriteLine("Exception Occured");
        }
        
    }
}

Output

exception handling in C#

Catching the exceptions without using exception classes

If we don't know about the specific class that should be used to catch the particular exception, then we can also handle/catch the exception by using the "catch" keyword only. There is no need to use the class name, consider the below program in which we are not specifying any exception class.

using System;

class Program
{
    static void Main()
    {
       
        int result  = 0;
        int num = 0;

        try
        {
            result = 500 / num;
            Console.WriteLine("This line will not execute");
        }
        catch 
        {
            Console.WriteLine("Exception occurred in try block");
        }
    }
}

Output

Exception occurred in try block





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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.