C# – Handling Multiple Exceptions

Handling multiple exceptions with more than one catch block:

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");
		}
	}
}

Handling multiple exceptions with single catch block:

using System;
public class Program
{
	public static void Main(string[] args)
	{
		try
		{
			Console.WriteLine("Enter First Number");
			int a = int.Parse(Console.ReadLine());
			Console.WriteLine("Enter Second Number");
			int b = int.Parse(Console.ReadLine());
			int res = a / b;
			Console.WriteLine("Result: " + res);
		}
		catch (Exception e)
		{
			Console.WriteLine("Exception : " + e.Message);
		}
	}
}

Handling exceptions with Logical OR(||) operator:

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(Exception ex)
		{
			if(ex is FormatException || ex is DivideByZeroException)
			{
				Console.WriteLine("Exception " + ex.GetType());
			}
		}
	}
}

Note: It is not possible to handle child type exception after handling parent type exception as shown below.

try
{
}
catch(Exception)
{
}
catch(FormatExcepiton)
{
}
Scroll to Top