Question
Which of the following correctly handles multiple
exceptions in Java?Solution
In Java, a single try block can handle multiple exceptions by attaching multiple catch blocks. Each catch block specifies a distinct exception type. The exception hierarchy determines the order of catch blocks—child exceptions must precede parent exceptions. Example: try { int a = 5 / 0; // ArithmeticException int[] arr = new int[2]; System.out.println(arr[3]); // ArrayIndexOutOfBoundsException } catch (ArithmeticException e) { System.out.println("Arithmetic Exception caught"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Index Out of Bounds Exception caught"); } catch (Exception e) { System.out.println("Generic Exception caught"); } ________________________________________ Why Other Options Are Incorrect: 1. Separate try blocks for each exception: This is inefficient and makes code less readable. A single try block with multiple catch blocks is the recommended approach. 2. Nesting try blocks within each other: This is not a standard practice unless the logic explicitly demands it. It can lead to convoluted and hard-to-maintain code. 3. Single catch block for all exceptions: While possible, this is a poor practice as it does not differentiate exception types, leading to less precise error handling. 4. Writing the exception type as a string: Java’s catch block requires exception classes, not strings, for type checking.
Where is the 'Startup 20 Shikhar' summit being organized under the G20 chairmanship of India?
Recently which bank has join hands with PFRDA to launch a digital platform which will allow customers to open NPS accounts using mobile phones?
Which country is India’s largest supplier of crude oil, surpassing China?
What is the key feature of the revamped ‘Baanknet’ e-auction portal launched by the DFS Secretary?
What was the theme of World Development Information Day 2021?
- Madhya Pradesh now has how many tiger reserves including Madhav National Park?
What is the objective of the three MoUs signed by the Khadi and Village Industries Commission (KVIC) with the Ministry of Micro, Small and Medium Enterp...
Where was the 2025 Laureus World Sports Awards ceremony held?
How many of the following statement/statements is/are correct regarding the ‘Ungalai Thedi, Ungal Ooril’ scheme in Tamil Nadu?
1. The scheme ...
SEBI has reconstituted its alternative investment policy advisory committee, which advises the capital markets regulator on a range of issues that impac...