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.
0
0
When clause in catch in C Sharp (C#)
Introduction
You want to catch an exception only if a certain variable has a specific value.
You want to handle errors differently based on the error message or error code.
You want to ignore some exceptions and let them pass if they don't meet a condition.
You want to add extra checks before deciding how to handle an error.
Syntax
C Sharp (C#)
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.
Examples
This catches the
IndexOutOfRangeException only if the error message contains the number 5.C Sharp (C#)
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."); }
This catches a
FormatException only if the current time is before noon.C Sharp (C#)
try { int.Parse("abc"); } catch (FormatException ex) when (DateTime.Now.Hour < 12) { Console.WriteLine("Morning format error caught."); }
Sample Program
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.
C Sharp (C#)
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."); } } }
OutputSuccess
Important Notes
The when clause helps avoid nested if checks inside catch blocks.
Use when to make your error handling clearer and more specific.
Summary
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.