0
0
C Sharp (C#)programming~3 mins

Why When clause in catch in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could catch only the errors you want without messy checks inside your catch blocks?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
try {
  // code
} catch (Exception ex) {
  if (ex.Message.Contains("timeout")) {
    // handle timeout
  } else {
    throw;
  }
}
After
try {
  // code
} catch (Exception ex) when (ex.Message.Contains("timeout")) {
  // handle timeout
}
What It Enables

This lets you write simpler, more readable error handling that reacts only to the exact problems you want to catch.

Real Life Example

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.

Key Takeaways

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.