पाठ 28 / 38

एक्सेप्शन

try / catch / finally से विफलताएँ संभालें, checked बनाम unchecked पहचानें, try-with-resources से संसाधन मुक्त करें, और त्रुटियाँ चुपचाप न दबाएँ।

checked बनाम unchecked

Checked एक्सेप्शन को throws या catch करना अनिवार्य है (जैसे IOException)। Unchecked (जैसे NullPointerException) आमतौर पर बग होते हैं।

try-with-resources

try (...) में घोषित AutoCloseable अपने-आप बंद होता है, एक्सेप्शन आने पर भी।

try (var reader = Files.newBufferedReader(path)) {
    return reader.readLine();
} catch (IOException e) {
    throw new UncheckedIOException(e);
}

एक्सेप्शन न दबाएँ

खाली catch ब्लॉक विफलताओं को छुपाता है। कम-से-कम स्टैक ट्रेस लॉग करें या संदर्भ के साथ दोबारा फेंकें।