Govt. Exams
Entrance 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.
StackOverflowError occurs when stack memory exhausts due to deep recursion. If a method catches an exception and immediately rethrows it without modification, calling itself, stack frames accumulate until overflow. This is a runtime error, not a checked exception.
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.
In multi-catch blocks like 'catch(IOException | SQLException e)', the exception types must not have an inheritance relationship. You cannot do 'catch(Exception | IOException e)' because IOException is a subclass of Exception.
'throw' is a statement that explicitly throws an exception object. 'throws' is a clause in method signature indicating the method may throw specific checked exceptions. Example: throw new IOException(); vs public void method() throws IOException {}
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.
If finally has a return statement, it suppresses any exception from try/catch blocks. The return value from finally overrides exception propagation. This is generally considered bad practice as it masks exceptions.
try {
int x = 10/0;
} catch(ArithmeticException e) {
System.out.println("Caught");
} finally {
System.out.println("Finally");
}
System.out.println("After");
When ArithmeticException occurs, it's caught by the catch block printing 'Caught'. The finally block always executes, printing 'Finally'. Then normal program flow continues, printing 'After'.
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.