Entrance Exams
Govt. Exams
class MyException extends Exception {}
class MyRuntimeException extends RuntimeException {}
RuntimeException and its subclasses are unchecked, so they don't need to be caught or declared. Option A requires try-catch since MyException is checked.
try {
throw new Exception("Test");
} catch(Exception e) {
System.out.println("Caught");
throw new RuntimeException("New");
} finally {
System.out.println("Finally");
}
The finally block executes after catch block. 'Caught' is printed, then finally block prints 'Finally', and then RuntimeException is thrown.
Java 7 introduced multi-catch using the pipe (|) operator: catch(IOException | SQLException e). This allows handling multiple exception types in one block.
AutoCloseable (Java 7+) is the primary interface for try-with-resources. Closeable extends AutoCloseable. Both work with try-with-resources.
Proper cause chaining calls super(msg, cause) in constructor, leveraging Exception's constructor that accepts both message and cause.
Try-with-resources (Java 7+) automatically closes resources, handles suppressed exceptions, and closes in LIFO order without explicit close() calls.
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.