Entrance Exams
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.
Try-with-resources (Java 7+) automatically closes resources, handles suppressed exceptions, and closes in LIFO order without explicit close() calls.
Throwable is the superclass. Exception and Error are direct subclasses, and RuntimeException is a subclass of Exception.
printStackTrace() prints to System.err, while getStackTrace() returns an array of StackTraceElement objects. Both exist and serve different purposes.
public class MultiCatchTest {
public static void main(String[] args) {
try {
int[] arr = {1, 2};
int x = arr[5];
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Array or Null Error");
}
}
}
Multi-catch feature (Java 7+) allows handling multiple exceptions. ArrayIndexOutOfBoundsException is caught by the multi-catch block.
Custom exceptions should extend Exception (for checked) or RuntimeException (for unchecked) depending on usage requirements.
public class ChainTest {
public static void main(String[] args) {
try {
try {
throw new IOException("IO Error");
} catch (IOException e) {
throw new RuntimeException("Runtime Error", e);
}
} catch (RuntimeException e) {
System.out.println(e.getCause().getClass().getSimpleName());
}
}
}
getCause() returns the IOException that was wrapped. getClass().getSimpleName() returns 'IOException'.
Exception class provides multiple constructors including one with String message and another with String message and Throwable cause for exception chaining.
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.