Java Exception Handling Quiz Questions
Java Exception Handling Quiz Questions
When an array in Java is accessed with an index that is out of its bounds, an ArrayIndexOutOfBoundsException is thrown. This can be caught and handled within a try-catch block, as shown in Source 1 where accessing an index of 10 in an array of size 5 is managed in a catch block, printing 'Caught' .
When handling multiple exceptions in a try-catch block in Java, they should be caught from the most specific to the most general. This avoids unreachable code and ensures that the specific exceptions are handled first .
A checked exception cannot be thrown without being caught or declared in the throws clause of a method. Java enforces exception handling during compilation for checked exceptions to ensure that specific recovery actions are taken, unlike unchecked exceptions .
Using a finally block to suppress exceptions could lead to loss of critical exception information, misleading program outcomes, or unexpected behaviors because exceptions raised in try and catch blocks can be overridden by the finally block. This can complicate debugging and cause resource leaks if resources are incorrectly handled .
If System.exit(0) is invoked within a try block, it will terminate the program immediately, and any code in the finally block will not execute—illustrated by the scenario where nothing is printed after calling System.exit(0).
Attempting integer division by zero will throw an ArithmeticException because division by zero is undefined. If not explicitly caught, it will terminate the program unless the try block manages it with a catch, as demonstrated where 'Error' is printed when the ArithmeticException is caught .
A 'throw' statement is used to explicitly throw an exception; however, it must be used in a context where the exception can be declared or handled. In checked exceptions, the context should also include the corresponding throws declaration in the method signature unless the exception is caught within the method—ensuring error transparency and error handling mechanisms are in place .
The 'finally' block in Java will always execute after the try block, whether an exception is thrown or not, making it ideal for cleanup operations. For example, System.out.println("Done") in a finally block will execute even if an exception is not thrown in the try block as described in Q7 .
When using 'return' statements in both a try and a finally block, the 'return' in the finally block will override the one in the try block. This is exemplified in a method returning 2, not 1, when defined in a finally block after a try indicating a return of 1 .
Catching multiple exceptions in a single catch block separated by a comma is invalid because Java does not allow multi-variable declaration in a single catch block. Instead, from Java 7 onwards, multiple exceptions can be caught using a single catch block by using the pipe (|) operator .