Entrance Exams
Govt. Exams
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
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.
NumberFormatException is thrown when attempting to convert a string to a numeric type but the string does not have an appropriate format. It's an unchecked exception.
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.
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.
FileNotFoundException is a checked exception (extends IOException). Others are unchecked - ClassCastException and NullPointerException are RuntimeExceptions, StackOverflowError is an Error.
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.