Entrance Exams
Govt. Exams
Checked exceptions in constructors, instance initializers, and static initializers must be handled with try-catch or declared in throws (constructors only). This is enforced by Java compiler.
public class Test {
public static void main(String[] args) {
try {
System.out.println("In try");
return;
} catch (Exception e) {
System.out.println("In catch");
} finally {
System.out.println("In finally");
}
}
}
Try block executes printing 'In try', then return is encountered. Finally block still executes printing 'In finally' before method returns. Catch is skipped as no exception occurs.
Exception class has both checked subclasses (like IOException) and unchecked subclasses (like RuntimeException). Not all exceptions extending Exception are checked.
A return statement in finally will override and suppress any return value or exception from try/catch blocks. This is considered a bad practice.
NullPointerException is thrown when attempting to use an object reference that hasn't been instantiated. Java doesn't have NullArgumentException.
public class ExceptionDemo {
public static void main(String[] args) {
try {
int arr[] = new int[2];
arr[5] = 10;
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block");
}
}
}
ArrayIndexOutOfBoundsException is caught by Exception catch block, printing 'Exception caught'. Finally block always executes regardless, printing 'Finally block'.
try {
int x = 5/0;
} catch (NullPointerException e) {
System.out.println("Caught NPE");
}
5/0 throws ArithmeticException, not NullPointerException. The catch block only handles NPE, so ArithmeticException propagates to the caller.
throw explicitly throws an exception object; throws declares in method signature that exceptions may be thrown. Example: throw new IOException() vs public void method() throws IOException.
Try-with-resources automatically invokes close() on any resource implementing AutoCloseable interface. Multiple resources can be declared with semicolon separation.
If an exception occurs in finally, it will propagate and override any previous exception from try/catch blocks. However, in try-with-resources, exceptions are suppressed.