Entrance Exams
Govt. Exams
public void process() throws IOException {
try {
readFile();
} catch (FileNotFoundException e) {
// handle
}
}
What is the issue here?
Since FileNotFoundException is a subclass of IOException, and readFile() can throw IOException, it should be caught in a separate catch block or the method signature should only throw FileNotFoundException.
Only one catch block executes for a thrown exception. The first matching catch block is executed.
Checked exceptions must be either caught in a try-catch block or declared in the method signature with 'throws'. Failure to do so results in a compilation error.
Throwable is the root. It has two subclasses: Exception and Error. Exception has RuntimeException as a subclass. Checked exceptions extend Exception directly.
public void test() throws IOException {
// method body
}
What does 'throws' indicate?
The 'throws' keyword declares that a method might throw the specified checked exception. The responsibility of handling is passed to the caller of the method.
try {
int x = 5/0;
} catch(Exception e) {
System.out.println("Caught");
} catch(ArithmeticException ae) {
System.out.println("Arithmetic");
}
This is a compilation error. Catch blocks must be ordered from most specific to most general. ArithmeticException is more specific than Exception, so it should come first.
Try-with-resources (Java 7+) automatically closes resources implementing AutoCloseable. Resources are closed in reverse order. Multiple resources can be declared with semicolon separation.
FileNotFoundException is a checked exception (extends IOException). Others are unchecked - ClassCastException and NullPointerException are RuntimeExceptions, StackOverflowError is an Error.
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index");
} catch(Exception e) {
System.out.println("Exception");
}
ArrayIndexOutOfBoundsException is thrown and caught by the first catch block. The second catch block is not executed. Only the most specific matching catch block executes.
try {
throw new Exception("Test");
} catch(Exception e) {
System.out.println("Caught");
} finally {
System.out.println("Finally");
}
The exception is caught and prints "Caught". The finally block always executes after try-catch, printing "Finally". Output: Caught Finally