MCAWALA

Java Vertical Menu

Java Exception Handling क्या है? – आसान हिंदी में समझें

🛑 Exception Handling का मतलब क्या है?

जब हम कोई Java प्रोग्राम लिखते हैं, तो कभी-कभी कोड में ऐसी गलतियां (errors) हो सकती हैं जिन्हें कंप्यूटर समझ नहीं पाता और प्रोग्राम अचानक बंद हो जाता है। इन गलतियों को Exceptions कहते हैं। Exception Handling वह प्रक्रिया है जिससे हम इन Errors को कंट्रोल करते हैं और प्रोग्राम को क्रैश होने से बचाते हैं।

🧰 Java में Exception Handling के मुख्य keywords:

  • try: उस कोड को लिखते हैं जिसमें Exception आने की संभावना होती है।
  • catch: Exception आने पर इस ब्लॉक में कोड execute होता है, जिससे हम error को संभालते हैं।
  • finally: यह ब्लॉक try-catch के बाद हमेशा execute होता है, चाहे Exception आए या नहीं।
  • throw: यह keyword manually Exception को फेंकने के लिए उपयोग होता है।
  • throws: यह बताने के लिए कि कोई method Exception फेंक सकता है।

Example:

public class Test {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int c = a / b;  // यह जगह Exception आएगा (ArithmeticException)
            System.out.println("Result: " + c);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        } finally {
            System.out.println("This block always executes.");
        }
    }
}

Output:

Error: Division by zero is not allowed.
This block always executes.

Types of Exceptions:

  • Checked Exception: Compiler समय पता चलता है, जैसे FileNotFoundException।
  • Unchecked Exception: Runtime में पता चलता है, जैसे ArithmeticException, NullPointerException।
  • Error: Serious problems जो usually handle नहीं किए जाते, जैसे OutOfMemoryError।

Exception Handling के फायदे:

  • प्रोग्राम crash नहीं होता।
  • Error messages को user-friendly बनाया जा सकता है।
  • प्रोग्राम का flow control में रहता है।
  • Debugging आसान होती है।

निष्कर्ष:

Java Exception Handling से हम प्रोग्राम को और reliable और error-resistant बनाते हैं। try-catch-finally जैसे constructs के जरिए हम errors को पकड़कर अच्छे से मैनेज कर सकते हैं।