← Back to C# Course | Chapter 10: Exception Handling | Lesson 5 of 6

Exception Filters (when) का उपयोग

एक exception filter किसी catch में एक condition जोड़ता है, जैसे एक goalkeeper जो सिर्फ एक corner पर निशाने लगाए shots रोकता है। catch किसी error को सिर्फ तभी handle करता है जब अतिरिक्त condition true हो।

In this page:

  1. Exception Filters (when)
Syntax
csharp
catch (ExceptionType ex) when (condition)
{
    // handled only if condition is true
}

Exception Filters (when)

एक when clause किसी catch block में एक boolean condition जोड़ता है, इसलिए यह सिर्फ तभी exception handle करता है जब वह condition भी true हो।

अगर condition false हो, तो C# अगले catch block को ऐसे देखता है जैसे यह बिल्कुल मेल नहीं खाया। यह किसी check के आधार पर तुरंत फिर से throw करने के लिए किसी exception को catch करने से बचाता है।

Note: Exception filters एक जैसी exception type को किसी error code या property के आधार पर अलग तरीके से handle करने के लिए उपयोगी हैं।

उदाहरण: Exception Filters (when)

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            throw new InvalidOperationException("critical failure");
        }
        catch (InvalidOperationException ex) when (ex.Message.Contains("critical"))
        {
            Console.WriteLine("Handled critical error: " + ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Handled general error: " + ex.Message);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. when filter के बजाय catch (Exception ex) { if (...) { ... } else { throw ex; } } का उपयोग करना, क्योंकि throw ex; stack trace reset करता है जबकि एक filter original exception को बिना छुए छोड़ देता है।
  2. यह उम्मीद करना कि condition false होने पर catch ... when (condition) block चलेगा; इसे skip कर दिया जाता है, और exception अगले catch पर जाता है या unhandled हो जाता है।
  3. when condition के अंदर ऐसा code रखना जो खुद throw कर सके, क्योंकि किसी filter में फेंका गया exception निगल लिया जाता है और false माना जाता है, जो bug छुपा देता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.