Entrance Exams
Govt. Exams
public class FinallyTest {
public static int getValue() {
try {
return 10;
} finally {
System.out.println("Finally");
}
}
public static void main(String[] args) {
System.out.println(getValue());
}
}
finally block executes before the return statement completes. System.out.println in finally executes first, then the return value 10 is printed.
IllegalMonitorStateException is thrown when an invalid monitor state operation occurs, such as calling notify() on an object not owned by the current thread.
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.
public class Test {
public static void main(String[] args) {
try {
System.out.println("In try");
return;
} catch (Exception e) {
System.out.println("In catch");
} finally {
System.out.println("In finally");
}
}
}
Try block executes printing 'In try', then return is encountered. Finally block still executes printing 'In finally' before method returns. Catch is skipped as no exception occurs.
A return statement in finally will override and suppress any return value or exception from try/catch blocks. This is considered a bad practice.
public class ExceptionDemo {
public static void main(String[] args) {
try {
int arr[] = new int[2];
arr[5] = 10;
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block");
}
}
}
ArrayIndexOutOfBoundsException is caught by Exception catch block, printing 'Exception caught'. Finally block always executes regardless, printing 'Finally block'.
try {
int x = 5/0;
} catch (NullPointerException e) {
System.out.println("Caught NPE");
}
5/0 throws ArithmeticException, not NullPointerException. The catch block only handles NPE, so ArithmeticException propagates to the caller.
Try-with-resources automatically invokes close() on any resource implementing AutoCloseable interface. Multiple resources can be declared with semicolon separation.
If an exception occurs in finally, it will propagate and override any previous exception from try/catch blocks. However, in try-with-resources, exceptions are suppressed.