What if you could catch only the errors you want without messy checks inside your catch blocks?
Why When clause in catch in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a program that can throw many types of errors, and you want to handle some errors only if certain conditions are true. Without a way to check conditions in your error handler, you might end up writing many repeated catch blocks or complicated code inside catch blocks.
Manually checking error details inside a catch block makes your code messy and hard to read. You might catch an error, then write extra if-statements to decide what to do. This slows down debugging and increases chances of mistakes.
The When clause in catch lets you add a condition directly to the catch block. This means you only catch errors that meet your condition, keeping your code clean and clear. It helps you handle specific cases without extra checks inside the catch.
try { // code } catch (Exception ex) { if (ex.Message.Contains("timeout")) { // handle timeout } else { throw; } }
try { // code } catch (Exception ex) when (ex.Message.Contains("timeout")) { // handle timeout }
This lets you write simpler, more readable error handling that reacts only to the exact problems you want to catch.
For example, if your program calls a web service, you can catch only timeout errors to retry the request, while letting other errors pass through.
Manually checking errors inside catch blocks is messy and error-prone.
The When clause adds conditions directly to catch blocks for cleaner code.
This improves readability and precise error handling.