How to Use 'when' in Catch Blocks in C#
In C#, you can use the
when keyword in a catch block to add a condition that filters which exceptions the block handles. This allows you to catch exceptions only when a specific condition is true, making error handling more precise and readable.Syntax
The when keyword is used after the exception type in a catch block to specify a condition that must be true for the catch block to execute.
Structure:
catch (ExceptionType ex) when (condition): Catches exceptions ofExceptionTypeonly ifconditionevaluates to true.
csharp
try { // code that may throw } catch (ExceptionType ex) when (condition) { // handle exception only if condition is true }
Example
This example shows how to catch a DivideByZeroException only when the divisor is zero, using a variable captured outside the try block.
csharp
using System; class Program { static void Main() { int divisor = 0; try { int result = 10 / divisor; } catch (DivideByZeroException ex) when (divisor == 0) { Console.WriteLine("Caught DivideByZeroException because divisor is zero."); } catch (DivideByZeroException ex) { Console.WriteLine("Caught DivideByZeroException for other reasons."); } } }
Output
Caught DivideByZeroException because divisor is zero.
Common Pitfalls
- Using
whenwithout a condition or with a condition that always evaluates tofalsemeans the catch block will never run. - Variables used in the
whencondition must be in scope and accessible. - Do not put complex logic in the
whencondition; keep it simple to avoid confusion. - Remember that exceptions not matching the
whencondition will continue to look for other catch blocks or propagate.
csharp
try { // code } catch (Exception ex) when (false) // This catch block never runs { // unreachable code } // Correct usage: try { // code } catch (Exception ex) when (ex.Message.Contains("specific")) { // handle only if message contains "specific" }
Quick Reference
Use when in catch to filter exceptions by condition.
- Place
when (condition)after the exception type. - Condition must be a boolean expression.
- Helps write cleaner and more specific error handling.
Key Takeaways
Use
when in catch blocks to handle exceptions only if a condition is true.The condition in
when must be a boolean expression accessible in the catch scope.Exceptions not matching the
when condition will be passed to other catch blocks or propagate.Keep
when conditions simple to maintain clear and readable code.Using
when improves precision in exception handling and avoids unnecessary catch executions.