try / catch / finally कैसे काम करता है
try, catch, और finally एक safety net हैं: कुछ risky आज़माएं, गिरने पर समस्या पकड़ें, और आखिर में चाहे जो भी हो साफ़-सफ़ाई करें। यह आपके program को crash होने से बचाता है।
In this page:
Syntax
try
{
// code that might throw
}
catch (ExceptionType ex)
{
// handle the error
}
finally
{
// always runs
}
try / catch / finally
एक try block में ऐसा code होता है जो exception फेंक सकता है; एक matching catch block अगर कोई हो तो उसे handle करता है।
finally बाद में चलता है चाहे कोई exception फेंका गया हो या नहीं, इसे cleanup code के लिए सही जगह बनाते हुए। Execution exception के point से सीधे सबसे नज़दीकी matching catch पर jump करता है।
Note:
finally तब भी चलता है जब try या catch block में एक return statement हो।उदाहरण: try / catch / finally
using System;
class Program
{
static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Caught: " + ex.Message);
}
finally
{
Console.WriteLine("Cleanup complete");
}
}
}
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. #}
आम गलतियां
Exceptioncatch करना और catch block को खाली छोड़ देना, जो असली errors छुपाता है।- specific catches से पहले एक general
catch (Exception)रखना, जो एक compile error है। - हमेशा चलना चाहिए वाले code को
finallyके बजायtryमें रखना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: