In C# 6.0, a new feature was introduced which allowed the execution of catch blocks, based on a specific condition when an exception occurs. This means, in a try-catch block, with multiple catch blocks, we can decide which catch block should get executed based on our requirement.
This can be implemented easily by adding the where condition along with the catch blocks. For example, in the following code, we can force the execution of first catch block, if the value of i is greater than 5. Else, it will execute the second block.
- static void Main(string[] args)
- {
- int i = 5;
- try
- {
- int a = 0;
- int b = 5;
- int c = b / a;
- }
- catch (Exception) when (i > 5)
- {
- throw;
- }
- catch (Exception) when (i <= 5)
- {
- throw;
- }
- Console.ReadKey();
- }
Run the application and see the result.
Simple, easy to use, and very helpful feature. Happy coding...!!!