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

When clause in catch in C Sharp (C#) - Deep Dive

Choose your learning style9 modes available
Overview - When clause in catch
What is it?
The 'when' clause in a catch block in C# lets you add a condition to decide if the catch block should handle an exception. Instead of catching every exception of a certain type, you can catch only those that meet specific criteria. This helps make error handling more precise and clear. It works by checking the condition before running the catch block code.
Why it matters
Without the 'when' clause, catch blocks handle all exceptions of a type, even if some don't need special handling. This can lead to catching errors too broadly, hiding real problems or making debugging harder. The 'when' clause lets you filter exceptions, so your program reacts only to the right errors, improving reliability and making your code easier to maintain.
Where it fits
Before learning 'when' clauses, you should understand basic try-catch error handling in C#. After mastering 'when' clauses, you can explore advanced exception handling patterns like custom exception types, exception filters, and best practices for logging and recovery.
Mental Model
Core Idea
A 'when' clause acts like a filter on exceptions, letting you catch only those that meet a specific condition.
Think of it like...
Imagine a security guard who only lets people in if they have a ticket and are wearing a red hat. The 'when' clause is like the guard's rule checking the hat color before allowing entry.
try {
  ┌───────────────┐
  │ Code runs     │
  └───────────────┘
} catch (Exception e) when (condition) {
  ┌─────────────────────────────┐
  │ If 'condition' is true,     │
  │ handle exception here       │
  └─────────────────────────────┘
} else {
  ┌─────────────────────────────┐
  │ Exception passes to next     │
  │ catch block or crashes       │
  └─────────────────────────────┘
}
Build-Up - 6 Steps
1
FoundationBasic try-catch error handling
🤔
Concept: Learn how to catch exceptions using try and catch blocks.
In C#, you use try to wrap code that might cause an error. If an error happens, the catch block runs to handle it. For example: try { int x = int.Parse("abc"); // This causes an error } catch (FormatException e) { Console.WriteLine("Invalid number format."); }
Result
The program prints: Invalid number format.
Understanding basic try-catch is essential because it lets you handle errors gracefully instead of crashing your program.
2
FoundationCatching exceptions by type
🤔
Concept: Catch blocks can specify the type of exception they handle.
You can catch specific exceptions by naming their type in catch. For example: try { int[] arr = new int[2]; Console.WriteLine(arr[5]); // Index out of range } catch (IndexOutOfRangeException e) { Console.WriteLine("Index error caught."); }
Result
The program prints: Index error caught.
Catching by type helps you respond differently to different errors, making your error handling more precise.
3
IntermediateIntroducing the 'when' clause in catch
🤔Before reading on: do you think a catch block with a 'when' clause runs for all exceptions of that type or only some? Commit to your answer.
Concept: The 'when' clause adds a condition to a catch block, so it only runs if the condition is true.
You can add 'when (condition)' after the exception type in catch. For example: try { throw new Exception("Error code 42"); } catch (Exception e) when (e.Message.Contains("42")) { Console.WriteLine("Caught error with code 42."); }
Result
The program prints: Caught error with code 42.
Knowing that 'when' filters exceptions lets you handle only the errors you want, avoiding unnecessary catch blocks.
4
IntermediateMultiple catch blocks with 'when' clauses
🤔Before reading on: do you think multiple catch blocks with 'when' clauses can handle the same exception? Commit to your answer.
Concept: You can have several catch blocks with different 'when' conditions to handle exceptions differently based on details.
Example: try { throw new Exception("Error 1"); } catch (Exception e) when (e.Message.Contains("1")) { Console.WriteLine("Handled error 1."); } catch (Exception e) when (e.Message.Contains("2")) { Console.WriteLine("Handled error 2."); }
Result
The program prints: Handled error 1.
Using multiple 'when' clauses lets you write clear, specific error handlers without complex if-else inside catch blocks.
5
AdvancedException filters vs. catch block code
🤔Before reading on: do you think the 'when' condition runs before or after the catch block starts? Commit to your answer.
Concept: 'when' conditions run before the catch block executes, so exceptions not matching the condition continue searching for other handlers.
This means: try { throw new Exception("Test"); } catch (Exception e) when (false) { Console.WriteLine("Won't run."); } catch (Exception e) { Console.WriteLine("Runs because first filter failed."); }
Result
The program prints: Runs because first filter failed.
Understanding that 'when' filters run before catch code prevents confusion about why some catch blocks don't execute.
6
ExpertPerformance and debugging with 'when' clauses
🤔Before reading on: do you think 'when' clauses affect how exceptions appear in debuggers? Commit to your answer.
Concept: 'when' clauses can improve performance by avoiding unnecessary catch blocks and affect how debuggers show exceptions because filters run before catch.
In debugging, exceptions filtered out by 'when' are not caught there, so the debugger may break differently. Also, 'when' clauses avoid catching exceptions that don't meet conditions, reducing overhead. Example: try { throw new Exception("Debug"); } catch (Exception e) when (e.Message == "No") { Console.WriteLine("Won't catch."); }
Result
The exception is not caught here and may be caught elsewhere or crash.
Knowing how 'when' affects debugging helps you diagnose why some exceptions seem to skip catch blocks.
Under the Hood
When an exception is thrown, the runtime looks for a matching catch block. If a catch has a 'when' clause, the runtime evaluates the condition before entering the catch block. If the condition is false, the runtime ignores that catch and continues searching. This filtering happens at the runtime exception dispatch level, allowing precise control without catching unwanted exceptions.
Why designed this way?
The 'when' clause was introduced to improve exception handling precision without nesting try-catch or adding complex if statements inside catch blocks. It allows cleaner, more readable code and better performance by avoiding unnecessary catch executions. Earlier, developers had to catch broadly and then filter inside catch, which was error-prone and less efficient.
Exception thrown
     │
     ▼
┌─────────────────────┐
│ Find catch blocks    │
│ matching exception   │
└─────────────────────┘
     │
     ▼
┌─────────────────────┐
│ Evaluate 'when'      │
│ condition if present │
└─────────────────────┘
     │ true / false
     ├─────────────┐
     ▼             ▼
┌─────────────┐  ┌─────────────┐
│ Enter catch │  │ Skip catch  │
│ block code  │  │ block       │
└─────────────┘  └─────────────┘
     │             │
     ▼             ▼
  Handle       Look for next
  exception    matching catch
Myth Busters - 4 Common Misconceptions
Quick: Does a catch block with a 'when' clause catch all exceptions of that type regardless of the condition? Commit to yes or no.
Common Belief:A catch block with a 'when' clause catches every exception of the specified type.
Tap to reveal reality
Reality:It only catches exceptions where the 'when' condition evaluates to true; others are ignored and passed on.
Why it matters:Believing this causes developers to think their catch block handles more errors than it does, leading to missed exceptions and bugs.
Quick: Does the 'when' condition run after the catch block starts executing? Commit to yes or no.
Common Belief:The 'when' condition runs inside the catch block after catching the exception.
Tap to reveal reality
Reality:The 'when' condition runs before entering the catch block; if false, the catch block does not run.
Why it matters:Misunderstanding this leads to confusion about why catch blocks don't execute and complicates debugging.
Quick: Can you use variables declared inside the catch block in the 'when' condition? Commit to yes or no.
Common Belief:You can use variables declared inside the catch block in the 'when' condition.
Tap to reveal reality
Reality:The 'when' condition runs before the catch block starts, so it cannot use variables declared inside it.
Why it matters:Trying to use such variables causes compile errors and wastes time debugging.
Quick: Does using 'when' clauses always improve performance? Commit to yes or no.
Common Belief:Adding 'when' clauses always makes exception handling faster.
Tap to reveal reality
Reality:'when' clauses can reduce unnecessary catch executions but add condition evaluation overhead; performance depends on usage.
Why it matters:Assuming automatic speedup may lead to overusing 'when' clauses in performance-critical code without measuring impact.
Expert Zone
1
Exception filters ('when' clauses) do not catch exceptions that occur inside the filter condition itself; such exceptions propagate normally.
2
The 'when' clause can access the exception object but cannot modify it or affect the exception propagation beyond filtering.
3
In async methods, 'when' clauses behave the same but can interact subtly with task-based exception handling and await points.
When NOT to use
Avoid 'when' clauses when the condition is complex or involves side effects, as it can make debugging harder and cause unexpected behavior. Instead, use explicit if-else inside catch blocks or separate catch blocks for clarity.
Production Patterns
In production, 'when' clauses are used to filter exceptions by error codes, messages, or custom properties, enabling targeted recovery or logging. They help keep catch blocks clean and focused, especially in layered architectures and libraries.
Connections
Pattern Matching
'when' clauses in catch blocks are similar to pattern matching guards that filter matches based on conditions.
Understanding 'when' clauses helps grasp how conditional logic can refine matches in pattern matching, improving code expressiveness.
Firewall Rules
'when' clauses act like firewall rules that filter network packets based on conditions before allowing or blocking them.
Knowing how firewalls filter traffic helps understand how 'when' clauses filter exceptions before handling.
Selective Attention in Psychology
'when' clauses resemble selective attention, focusing on certain stimuli (exceptions) while ignoring others.
This connection shows how filtering mechanisms in programming mirror cognitive processes of focusing on relevant information.
Common Pitfalls
#1Using variables declared inside catch block in 'when' condition.
Wrong approach:try { throw new Exception("Error"); } catch (Exception e) when (someVar == 5) { int someVar = 5; Console.WriteLine("Caught."); }
Correct approach:int someVar = 5; try { throw new Exception("Error"); } catch (Exception e) when (someVar == 5) { Console.WriteLine("Caught."); }
Root cause:'when' condition runs before catch block, so variables inside catch are not yet declared.
#2Assuming catch block runs even if 'when' condition is false.
Wrong approach:try { throw new Exception("Error"); } catch (Exception e) when (false) { Console.WriteLine("This runs."); }
Correct approach:try { throw new Exception("Error"); } catch (Exception e) { Console.WriteLine("This runs."); }
Root cause:'when' condition filters exceptions before catch block; false means catch block is skipped.
#3Using complex or side-effect code inside 'when' condition.
Wrong approach:try { throw new Exception("Error"); } catch (Exception e) when (LogError(e) && e.Message.Contains("Error")) { Console.WriteLine("Caught."); } bool LogError(Exception ex) { Console.WriteLine("Logging"); return true; }
Correct approach:try { throw new Exception("Error"); } catch (Exception e) when (e.Message.Contains("Error")) { LogError(e); Console.WriteLine("Caught."); } void LogError(Exception ex) { Console.WriteLine("Logging"); }
Root cause:'when' conditions should be side-effect free; side effects can cause unexpected behavior and debugging difficulty.
Key Takeaways
The 'when' clause in catch blocks filters exceptions by condition before handling them, making error handling more precise.
It runs before the catch block code, so if the condition is false, the catch block is skipped and the exception continues searching for handlers.
Using 'when' clauses helps avoid broad catch blocks and complex if-else inside catch, improving code clarity and maintainability.
Misusing 'when' clauses, like referencing undeclared variables or adding side effects, leads to errors and debugging challenges.
Understanding 'when' clauses deeply improves your ability to write robust, efficient, and clear exception handling in C#.