TLDR;
Use when with a catch block to get hold of exceptions without unwinding the stack.
You can use it to handle exception based on specific property, condition or context.
we were catching exceptions just fine before the introduction of when keyword. I must say, its a good feature released in C# 6.
catch (ExceptionType e) when (expression)
expression should return a boolean value, if the result is true the ExceptionHandler executes. The only difference I found, it gives you provision to check the variables value in a debug session. I dont see any production value in this feature.
Exception filters (when):
The filter expression is evaluated before the stack is unwound. This means the original call stack and all local variables remain intact during filter evaluation.
-
Handling exception using specific property
catch (IOException ex) when (ex.Message.Contains("access denied")) { Console.WriteLine("File access denied. Check permissions."); Console.WriteLine(ex.StackTrace); }
catch (IOException ex) when (ex.Message.Contains("not found")) { Console.WriteLine("File not found. Verify the path."); Console.WriteLine(ex.StackTrace); }
catch (Exception ex) { Console.WriteLine("general catch all"); Console.WriteLine(ex.StackTrace); }
You wont get to see any difference in the above 3 stack traces printed in the exceptions.
It helps us in examining exception before deciding to handle them and lets us handle based on the context.
catch (IOException ex) when (filePath.contains(@"c:\users"))
{
Console.WriteLine($"Network file operation failed: {ex.Message}");
}
Why do we need multiple catch blocks? why not just use a catchall with (Exception)
Catching specific exceptions can help you take more granular decision based on the situation.It can tell you a lot more about the error occurred using the properties specific to that Exception type.
Yes they all are derived from Exception but every class has some specific properties limited to them and you can access them if you catch them.
Exception handling is a feature that helps the developer to avoid getting embarrassed in front of the client.
But using when clause in exception handling is a feature that helps the developer with getting to know about the error better.