Entrance Exams
Govt. Exams
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.
Exception chaining preserves the stack trace and cause information: throw new RuntimeException("msg", originalException). This helps in debugging by maintaining the complete exception history.
DatabaseConnectionException should be checked (extends Exception) as it's a serious, recoverable error requiring explicit handling. Business logic exceptions can be unchecked.