Try with Multiple Catch Blocks: One try block can have multiple catch blocks to handle different types of exceptions occur in different lines of code.
Program to read 2 numbers and perform division: In this program, we need to handle two exceptions
- FormatException: If the input is invalid
- DivideByZeroException: If the denominator is zero
using System;
public class Program
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter 2 integers to add : ");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = a/b;
Console.WriteLine("Result = " + c);
}
catch(FormatException)
{
Console.WriteLine("Exception : Invalid input given");
}
catch(DivideByZeroException)
{
Console.WriteLine("Exception : Denominator is zero");
}
}
}
We can handle Multiple exceptions in following ways:
Try with Multiple Catch blocks: It is useful to provide different message to different exceptions.
try{
code…
}
catch(Exception1 e1){
}
catch(Exception2 e2){
}
catch object using Exception class: Same logic to handle all exceptions
try
{
Code….
}
catch(Exception e){
}
Using OR: Related exceptions can handle with single catch block
try
{
Code….
}
catch(Exception ex)
{
if(ex is FormatException || ex is DivideByZeroException)
{
Console.WriteLine("Exception " + ex.GetType());
}
}