How to catch multiple exceptions at once in C#
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.
Catching multiple exceptions at once using when
In this approach, we catch all the exceptions inside a single catch block using the when keyword.
Example
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");}}}
Explanation
In the code snippet above, inside the main function:
- Lines 7–10: We create a
tryblock. - Line 9: We deliberately throw a
DivideByZeroException.
- Lines 12–18: We catch multiple exceptions at once using
whenand separate each caught exception by an||(OR) operator.
Catching multiple exceptions at once using switch-case
In this approach, we catch all the exceptions inside a single catch block using the switch-case statement.
Example
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;}}}}
Explanation
In the code snippet above, inside the main function:
- Lines 7–10: We create a
tryblock. - Line 9: We deliberately throw a
DivideByZeroException.
- Lines 12–27: We catch multiple exceptions at once using the
switch-casestatement. We first get the type of exception usingGetType(), convert it to a string usingToString(), and then pass it to theswitch()function. We list all the exceptions that are caught using thecasestatement.