Entrance Exams
Govt. Exams
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.
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.
public class Test {
public static void main(String[] args) {
int x = 0;
try {
x = 5;
System.out.println(x / 0);
x = 10;
} catch (ArithmeticException e) {
x = 15;
} finally {
System.out.println(x);
}
}
}
x becomes 5, then ArithmeticException occurs. x becomes 15 in catch block. Finally block prints 15.
Checked exceptions must be either caught or declared using throws. Ignoring them causes compilation error.
try (FileReader fr = new FileReader("file.txt")) {
// use fr
} catch (IOException e) {
// handle
}
What will happen to 'fr' after the try block?
Try-with-resources automatically closes resources implementing AutoCloseable interface, regardless of normal or exceptional termination.
If an exception is thrown in finally block, it replaces the original exception that was being propagated. The original exception is lost.