Checked exception
RuntimeException के विपरीत, सभी checked exceptions के लिए try-catch ब्लॉक होना अनिवार्य है, वरना कोड compile नहीं होगा, चलना तो दूर की बात है. इस अभ्यास में, आप देखेंगे कि आपको checked exception के चारों तरफ try/catch जोड़ना ही पड़ेगा, नहीं तो एप्लिकेशन compile नहीं होगा और run भी नहीं होगा.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में डेटा टाइप्स और Exceptions
अभ्यास निर्देश
- बिना कोई बदलाव किए नमूना कोड चलाएँ और देखें कि
Class.forName()कॉल के लिए हैंडलिंग चाहिए; अगर इसे हैंडल नहीं किया गया, तो compile error (error: compilation failed) आएगा. - try, catch, और catch ब्लॉक में दिखाया जाने वाला message uncomment करें.
- अब एप्लिकेशन दोबारा चलाने की कोशिश करें और देखें कि checked exception हैंडल होने के कारण एप्लिकेशन compile और run हो जाता है.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
public class CheckedExceptionHandling {
public static void main(String[] args) {
// Uncomment the try block
// try {
Class.forName("java.util.ArrayList");
// Uncomment the catch block for ClassNotFoundException
// } catch (ClassNotFoundException e) {
// Uncomment the message for the exception
// System.out.println("Work goes here to recover from the checked exception");
// Uncomment the end of the try/catch
// }
System.out.println("Work complete");
}
}