🔴 Advanced · Lesson 23
Exception Handling
Exception Handling क्या है?
Exception program चलते समय होने वाली एक अनचाही घटना है जो सामान्य flow को रोक देती है — जैसे zero से भाग देना, array की सीमा से बाहर जाना, या गायब file खोलना। Exception handling ऐसी errors को crash हुए बिना संभालने देता है।
पाँच Keywords
| Keyword | उपयोग |
|---|---|
try | जोखिम भरे code को लपेटता है। |
catch | exception होने पर संभालता है। |
finally | हमेशा चलता है (cleanup)। |
throw | manually exception फेंकता है। |
throws | बताता है कि method exception फेंक सकता है। |
उदाहरण
Java
try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Done"); }
▶ Output
Cannot divide by zero Done
Checked vs Unchecked
| प्रकार | कब check | उदाहरण |
|---|---|---|
| Checked | Compile time (संभालना ज़रूरी) | IOException, SQLException |
| Unchecked | Runtime | ArithmeticException, NullPointerException |
💡 क्यों संभालें?
बिना handling के एक error पूरा program crash कर देती है। handling से friendly message दिखाकर program चलता रहता है।
⚠️ आम गलती
खाली catch {} block कभी न छोड़ें — यह bugs छुपाता है। कम से कम error log करें।
सारांश
- Exceptions normal flow रोकती हैं; handling crash रोकती है।
- Keywords: try, catch, finally, throw, throws।
finallyहमेशा चलता है; checked ज़रूरी, unchecked runtime पर।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
