The when clause in a catch block lets you handle exceptions only if a specific condition is true. This helps you write cleaner and more precise error handling.
When clause in catch in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
try { // code that might throw } catch (ExceptionType ex) when (condition) { // handle exception only if condition is true }
The when condition is a boolean expression evaluated when an exception is caught.
If the condition is false, the exception is not handled here and can be caught by another catch block or propagate up.
IndexOutOfRangeException only if the error message contains the number 5.try { int[] numbers = {1, 2, 3}; int x = numbers[5]; } catch (IndexOutOfRangeException ex) when (ex.Message.Contains("5")) { Console.WriteLine("Caught index error with 5 in message."); }
FormatException only if the current time is before noon.try { int.Parse("abc"); } catch (FormatException ex) when (DateTime.Now.Hour < 12) { Console.WriteLine("Morning format error caught."); }
This program throws an exception with a message depending on the number. The first catch block only handles exceptions with "big" in the message. Others are handled by the second catch.
using System; class Program { static void Main() { int number = 10; try { if (number > 5) throw new InvalidOperationException("Number is too big"); else throw new InvalidOperationException("Number is small"); } catch (InvalidOperationException ex) when (ex.Message.Contains("big")) { Console.WriteLine("Caught exception for big number."); } catch (InvalidOperationException ex) { Console.WriteLine("Caught other invalid operation exception."); } } }
The when clause helps avoid nested if checks inside catch blocks.
Use when to make your error handling clearer and more specific.
The when clause adds a condition to a catch block.
It runs the catch block only if the condition is true.
This helps write cleaner and more precise error handling code.
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
