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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
What does the when clause do in a catch block in C#?
Solution
Step 1: Understand the purpose of the when clause
Thewhenclause adds a condition to acatchblock.Step 2: Effect of the when clause in exception handling
The catch block runs only if the condition afterwhenis true, otherwise it skips.Final Answer:
It adds a condition to run the catch block only if the condition is true. -> Option AQuick Check:
when clause = conditional catch [OK]
- Thinking when defines a new exception type
- Assuming catch runs always regardless of when
- Confusing when with finally block
Which of the following is the correct syntax to use a when clause in a catch block?
try {
// code
} catch (Exception ex) _____ {
// handle
}Solution
Step 1: Recall the correct keyword for condition in catch
The correct keyword to add a condition in catch iswhen.Step 2: Match the syntax with the options
Only when (ex.Message.Contains("error")) useswhencorrectly with the condition.Final Answer:
when (ex.Message.Contains("error")) -> Option DQuick Check:
Use 'when' keyword for catch condition [OK]
- Using if instead of when in catch
- Confusing when with where or while
- Missing parentheses after when
What will be the output of this code?
try {
throw new InvalidOperationException("Invalid operation");
} catch (InvalidOperationException ex) when (ex.Message.Contains("Invalid")) {
Console.WriteLine("Caught invalid operation");
} catch (Exception) {
Console.WriteLine("Caught general exception");
}Solution
Step 1: Identify the thrown exception and matching catch
The code throwsInvalidOperationExceptionwith message containing "Invalid".Step 2: Check the when condition in the first catch
The first catch has a when clause checking if message contains "Invalid" which is true, so it runs.Final Answer:
Caught invalid operation -> Option BQuick Check:
when condition true runs first catch [OK]
- Ignoring the when condition and picking second catch
- Assuming no output if when is used
- Confusing exception types
Find the error in this code snippet:
try {
// some code
} catch (Exception ex) when ex.Message == "Error" {
Console.WriteLine("Error caught");
}Solution
Step 1: Check syntax of when clause
The condition afterwhenmust be enclosed in parentheses.Step 2: Identify the missing parentheses in the code
The code useswhen ex.Message == "Error"without parentheses, which is invalid syntax.Final Answer:
Missing parentheses around the when condition -> Option CQuick Check:
when condition needs parentheses [OK]
- Omitting parentheses around when condition
- Thinking when can't be used with Exception
- Believing catch can't have code inside
Consider this code:
try {
throw new ArgumentNullException("param");
} catch (ArgumentNullException ex) when (ex.ParamName == "param") {
Console.WriteLine("Parameter error");
} catch (ArgumentNullException ex) {
Console.WriteLine("Other argument null error");
}What will be printed and why?
Solution
Step 1: Identify the thrown exception and its property
The code throwsArgumentNullExceptionwithParamNameset to "param".Step 2: Check the when clause condition in the first catch
The first catch has a when clause checking ifex.ParamName == "param", which is true, so this catch runs.Step 3: Understand catch block selection
The second catch is ignored because the first matching catch with true when condition handles the exception.Final Answer:
Parameter error, because the when condition matches the ParamName. -> Option AQuick Check:
when true catches first matching block [OK]
- Ignoring when condition and picking second catch
- Thinking duplicate catch causes error
- Assuming exception is uncaught
