Entrance Exams
Govt. Exams
The finally block executes unconditionally after try and/or catch blocks complete, making it ideal for resource cleanup. It runs even if try or catch blocks return.
Multiple exceptions are declared using comma-separated syntax in the throws clause. Parentheses and pipe operators are not valid syntax for this purpose.
SQLException is a checked exception that must be caught or declared. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are unchecked exceptions (RuntimeException subclasses).
When an exception is thrown and not caught, it propagates up the call stack until a matching catch block is found or the program terminates.
public class ExceptionTest {
public static void main(String[] args) {
try {
testMethod();
} catch (Exception e) {
System.out.println("Caught");
}
}
public static void testMethod() {
try {
throw new RuntimeException("Error");
} finally {
System.out.println("Finally");
}
}
}
Finally block executes first (prints 'Finally'), then the exception propagates to outer catch block which prints 'Caught'.
Try-with-resources requires resources to implement AutoCloseable interface. String doesn't implement it, so it cannot be used.
public static void main(String[] args) {
try {
System.out.println("A");
return;
} finally {
System.out.println("B");
}
}
What is the output?
Even with return in try block, finally block executes. So 'A' prints first, then 'B' before returning.
'throw' keyword actually throws an exception object. 'throws' keyword declares that a method throws a checked exception.
try {
// code
} catch (IOException | SQLException e) {
// handle
}
What is this syntax called?
This is called multi-catch or union catch syntax (Java 7+) allowing multiple exception types to be caught in one block using pipe operator.
Return in finally block overrides returns in try or catch blocks. The finally return value is what gets returned.