Entrance Exams
Govt. Exams
When exception chaining is explicitly used with initCause() or constructor parameters, the original exception becomes the cause of the new exception. Without explicit chaining, the original exception is lost. Exception chaining is not automatic in Java.
When try-with-resources encounters an exception while closing a resource, it's added to the suppressed exceptions list. If an exception was already thrown in try, the close exception is suppressed rather than replacing it. getSuppressed() returns array of these suppressed exceptions.
The innermost matching catch block executes first. If it doesn't rethrow the exception, the outer catch block won't execute. The exception is considered handled after the first matching catch block.
Error is not a subclass of Exception. Both Error and Exception extend Throwable. Errors like OutOfMemoryError, StackOverflowError cannot be caught by Exception handlers. They must be caught separately if needed.
Try-with-resources closes resources in LIFO (Last In, First Out) order. If you declare Resource1, then Resource2, Resource2 closes first, then Resource1. This ensures dependencies are respected.
try {
try {
throw new Exception("Inner");
} catch(Exception e) {
throw new RuntimeException("Outer");
}
} catch(RuntimeException e) {
System.out.println("Caught: " + e.getMessage());
}
The inner try catches Exception and throws RuntimeException. The outer catch catches RuntimeException and prints 'Caught: Outer'.
Try-with-resources automatically invokes close() on resources implementing AutoCloseable/Closeable. Syntax: try(Resource r = new Resource()) {...}
String str = "Java";
try {
int x = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid number");
} catch(Exception e) {
System.out.println("General exception");
}
Integer.parseInt("Java") throws NumberFormatException, which is caught by the first catch block. More specific exceptions should be caught before general ones.
The getCause() method returns the cause (underlying Throwable) of this Throwable. It's useful for exception chaining.
Comparing with null using == operator doesn't throw NPE. The other options call methods or unbox null values, which causes NullPointerException.