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.
NullPointerException is thrown when attempting to call a method or access a property on a null object reference in Java.
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.
Runnable is a functional interface, not related to exception hierarchy. Error and Exception are direct subclasses of Throwable. RuntimeException is a subclass of Exception.
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
A try block must be followed by either a catch block or a finally block (or both). A try block alone is not valid syntax.
IllegalArgumentException is thrown to indicate that a method has been passed an illegal or inappropriate argument. It is an unchecked exception.
int x = 10;
try {
x = x / 0;
} catch(ArithmeticException e) {
x = x + 5;
} finally {
x = x * 2;
}
System.out.println(x);
ArithmeticException is caught, x becomes 10+5=15. Finally block executes, x becomes 15*2=30. Finally block always executes regardless of exception.
IOException is a checked exception that must be caught or declared in the method signature. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are unchecked exceptions.