Exception Filters (when) का उपयोग
एक exception filter किसी catch में एक condition जोड़ता है, जैसे एक goalkeeper जो सिर्फ एक corner पर निशाने लगाए shots रोकता है। catch किसी error को सिर्फ तभी handle करता है जब अतिरिक्त condition true हो।
In this page:
Syntax
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)
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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
whenfilter के बजायcatch (Exception ex) { if (...) { ... } else { throw ex; } }का उपयोग करना, क्योंकिthrow ex;stack trace reset करता है जबकि एक filter original exception को बिना छुए छोड़ देता है।- यह उम्मीद करना कि condition false होने पर
catch ... when (condition)block चलेगा; इसे skip कर दिया जाता है, और exception अगलेcatchपर जाता है या unhandled हो जाता है। whencondition के अंदर ऐसा code रखना जो खुद throw कर सके, क्योंकि किसी filter में फेंका गया exception निगल लिया जाता है औरfalseमाना जाता है, जो bug छुपा देता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: