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...!!!
Simple, easy to use, and very helpful feature. Happy coding...!!!

Naveen BishtPosted Feb 15, 2017, 9:46 PM
great year, thanks
Joginder BangerPosted Feb 14, 2017, 4:01 AM
Yeah ...it's valuable tip. Thanks for sharing.
Sandip G PatilPosted Feb 13, 2017, 8:26 AM
Nice article...Well explained