Govt Exams
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.
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.
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.
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.
int result = 0;
try {
result = 10 / 0;
} catch(Exception e) {
result = 20;
return result;
} finally {
result = 30;
}
System.out.println(result);
Return statement in catch block prepares the return value (20). Finally block executes but return happens after finally, so 20 is returned even though finally sets result to 30.
I. catch(FileNotFoundException e)
II. catch(IOException e)
III. catch(Exception e)
Catch blocks should be ordered from most specific to most general exception types. FileNotFoundException is more specific than IOException, which is more specific than Exception.
Exception class is the parent of all checked exceptions. RuntimeException extends Exception but is unchecked. Error and Throwable are higher in hierarchy.
System.exit() terminates the JVM immediately. The finally block does not execute as the program terminates before reaching it.
StackOverflowError occurs from stack overflow due to excessive method calls. Local variables contribute to stack but won't cause overflow like recursion.