Skip to content

Add explanation of why the when contextual keyword is better than if/else in catch blocks #47887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Aug 7, 2025

This PR addresses the lack of explanation for why C#'s when contextual keyword provides advantages over using if/else statements inside catch blocks. The key technical difference is that exception filters don't unwind the call stack, while traditional catch blocks do.

Changes Made

Enhanced exception-handling-statements.md

Added a comprehensive "Exception filters vs. traditional exception handling" section that explains:

  • Exception filters (when) evaluate before stack unwinding, preserving the original call stack and local variables
  • Traditional catch blocks unwind the stack before entering the handler, potentially losing debugging information
  • Performance benefits when no filter matches (no unwinding overhead)
  • Cleaner code organization for multiple conditions on the same exception type

Updated when.md

Added context explaining the advantages of exception filters with a cross-reference to the detailed explanation in the exception handling statements documentation.

New Code Examples

Created comprehensive working examples in WhenFilterExamples.cs demonstrating:

  • Direct comparison between exception filters and if/else approaches
  • Multiple condition handling scenarios
  • Logging and diagnostic use cases that preserve debugging information

Technical Benefits Explained

The documentation now clearly explains why this approach is superior:

try
{
    ProcessFile();
}
catch (IOException ex) when (ex.Message.Contains("access denied"))
{
    // Filter evaluated before stack unwinding
    // Full debugging context still available
    HandleAccessDenied();
}
catch (IOException ex)
{
    // Traditional approach - stack already unwound
    if (ex.Message.Contains("not found"))
    {
        HandleNotFound();
    }
}

The exception filter approach is particularly valuable in production applications where preserving debugging information is crucial for diagnosing issues.

Fixes #40661.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.


Internal previews

📄 File 🔗 Preview link
docs/csharp/language-reference/keywords/when.md docs/csharp/language-reference/keywords/when
docs/csharp/language-reference/statements/exception-handling-statements.md docs/csharp/language-reference/statements/exception-handling-statements

@Copilot Copilot AI changed the title [WIP] Add explanation of why we need the when contextual keyword Add explanation of why the when contextual keyword is better than if/else in catch blocks Aug 7, 2025
@Copilot Copilot AI requested a review from BillWagner August 7, 2025 20:46
Copilot finished work on behalf of BillWagner August 7, 2025 20:46
Copy link
Member

@BillWagner BillWagner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good start.

Copilot finished work on behalf of BillWagner August 8, 2025 14:28
@Copilot Copilot AI requested a review from BillWagner August 8, 2025 14:28
Copilot finished work on behalf of BillWagner August 8, 2025 17:08
@BillWagner BillWagner marked this pull request as ready for review August 8, 2025 17:14
@BillWagner BillWagner requested a review from a team as a code owner August 8, 2025 17:14
@BillWagner BillWagner requested a review from adegeo August 8, 2025 17:14
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code comments should end in punctuation.

Comment on lines +102 to +103
- **Exception filters (`when`)**: The filter expression is evaluated *before* the stack is unwound. This means the original call stack and all local variables remain intact during filter evaluation.
- **Traditional `catch` blocks**: The stack is unwound *before* entering the catch block, potentially losing valuable debugging information.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Before" is italicized in both bullet points to add emphasis, which doesn't make much sense since they're trying to point out differences.


:::code language="csharp" source="snippets/exception-handling-statements/WhenFilterExamples.cs" id="ExceptionFilterVsIfElse":::

**Advantages of exception filters:**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know Copilot likes to add bolding using **, but it actually goes against style guidelines.


**Advantages of exception filters:**

1. **Better debugging experience**: Since the stack isn't unwound until a filter matches, debuggers can show the original point of failure with all local variables intact.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be a numbered list since it's not a sequential procedure.

Comment on lines +122 to +125
- Handle exceptions based on specific conditions or properties
- Preserve the original call stack for debugging
- Log or examine exceptions before deciding whether to handle them
- Handle the same exception type differently based on context
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add periods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add explanation of why we need the when contextual keyword
4 participants