Entrance Exams
Govt. Exams
public class Test {
public static void main(String[] args) {
try {
throw new Exception("Test");
} catch (Exception e) {
System.out.println("1");
} catch (Exception e) {
System.out.println("2");
}
}
}
Multiple catch blocks with the same exception type cause compilation error. Java doesn't allow duplicate catch blocks for identical exception types.
public class ExceptionTest {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught");
} finally {
System.out.println("Finally");
}
}
}
ArithmeticException is caught by the catch block printing 'Caught', then finally block executes printing 'Finally'.
The finally block always executes regardless of whether a return, break, continue, or exception occurs in try or catch blocks, unless System.exit() is called.
In try-with-resources, if an exception occurs in try and another in resource close(), the second is added as suppressed exception to the first using addSuppressed(), preserving all exception information.
throws declaration indicates the method may throw IOException. The caller is responsible for handling it with try-catch or declaring throws. The method doesn't always throw it.
Nested exception handling follows inner-to-outer order. Inner try-catch-finally completes fully, then control passes to outer blocks. Finally blocks execute in their respective scope order.
ArrayIndexOutOfBoundsException is thrown when attempting to access array elements with invalid indices. It's an unchecked exception extending RuntimeException.
Unchecked exceptions (RuntimeException subclasses) don't require explicit handling. If not caught, they propagate up the call stack, eventually terminating the thread if not caught anywhere.
The getCause() method returns the Throwable that caused the current exception, enabling exception chaining analysis and debugging.
Exception chaining wraps a caught exception within another exception using initCause() or constructor, preserving the original exception for debugging and stack trace analysis.