Govt Exams
public class ExceptionOrder {
public static void main(String[] args) {
try {
try {
throw new RuntimeException("Inner");
} catch (Exception e) {
throw new IOException("Outer");
}
} catch (IOException e) {
System.out.println("Caught IOException");
} catch (RuntimeException e) {
System.out.println("Caught RuntimeException");
}
}
}
IOException is a checked exception and must be declared in method signature or caught. The inner catch throws IOException which isn't caught immediately.
In try-with-resources, if an exception occurs in try and another in resource close(), the second is added as suppressed exception to the first using addSuppressed(), preserving all exception information.
Nested exception handling follows inner-to-outer order. Inner try-catch-finally completes fully, then control passes to outer blocks. Finally blocks execute in their respective scope order.
Checked exceptions in constructors, instance initializers, and static initializers must be handled with try-catch or declared in throws (constructors only). This is enforced by Java compiler.
Exception class has both checked subclasses (like IOException) and unchecked subclasses (like RuntimeException). Not all exceptions extending Exception are checked.
public class ExceptionTest {
public static void main(String[] args) {
try {
testMethod();
} catch (Exception e) {
System.out.println("Caught");
}
}
public static void testMethod() {
try {
throw new RuntimeException("Error");
} finally {
System.out.println("Finally");
}
}
}
Finally block executes first (prints 'Finally'), then the exception propagates to outer catch block which prints 'Caught'.
try {
try {
int x = 5/0;
} catch(NullPointerException e) {
System.out.println("Inner");
}
} catch(ArithmeticException e) {
System.out.println("Outer");
}
ArithmeticException is thrown by 5/0. Inner catch only catches NullPointerException, so it propagates to outer catch which handles ArithmeticException. Output: Outer
If an exception occurs in the finally block, it will replace any exception thrown in the try or catch block, and the new exception will be propagated.
try {
return 5;
} finally {
return 10;
}
What will be returned?
The finally block always executes, and if it contains a return statement, it overrides the return value from try or catch block. So 10 is returned.
AtomicInteger suffers from false sharing when multiple threads frequently update adjacent memory locations on the same CPU cache line. LongAdder uses striped updates across multiple cells, reducing contention. This is a 2024-25 performance optimization best practice for high-concurrency scenarios.