In C#, we manage exception handling using the try-catch
block. Multiple exceptions can be caught separately or at once, depending on the developer's choice.
In this shot, we'll see how to catch multiple exceptions at once.
when
In this approach, we catch all the exceptions inside a single catch block using the when
keyword.
using System;class HelloWorld{static void Main(){try {// throwing a divide by zero exceptionthrow new DivideByZeroException();}// catching multiple exceptions at once using 'when'catch (Exception e) when (e is NullReferenceException ||e is DivideByZeroException ||e is IndexOutOfRangeException) {Console.WriteLine("Exception occured");}}}
In the code snippet above, inside the main function:
try
block.DivideByZeroException
.when
and separate each caught exception by an ||
(OR) operator.switch-case
In this approach, we catch all the exceptions inside a single catch block using the switch-case
statement.
using System;class HelloWorld{static void Main(){try {// throwing a divide by zero exceptionthrow new DivideByZeroException();}// catching multiple exceptions at once using 'switch case'catch (Exception e) {switch (e.GetType().ToString()) {case "System.NullReferenceException":Console.WriteLine("NullReferenceException occured");break;case "System.DivideByZeroException":Console.WriteLine("DivideByZeroException occured");break;case "System.IndexOutOfRangeException":Console.WriteLine("IndexOutOfRangeException occured");break;default:Console.WriteLine("Exception occured");break;}}}}
In the code snippet above, inside the main function:
try
block.DivideByZeroException
.switch-case
statement. We first get the type of exception using GetType()
, convert it to a string using ToString()
, and then pass it to the switch()
function. We list all the exceptions that are caught using the case
statement.