Entrance Exams
Govt. Exams
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.
public void process() throws IOException {
try {
readFile();
} catch (FileNotFoundException e) {
// handle
}
}
What is the issue here?
Since FileNotFoundException is a subclass of IOException, and readFile() can throw IOException, it should be caught in a separate catch block or the method signature should only throw FileNotFoundException.
Only one catch block executes for a thrown exception. The first matching catch block is executed.
public class Demo {
public static void main(String[] args) {
try {
System.out.println("A");
throw new Exception("Test");
System.out.println("B");
} catch (Exception e) {
System.out.println("C");
}
}
}
After 'A' is printed, exception is thrown. Statement 'B' is never executed. Catch block prints 'C'.
NumberFormatException is thrown by Integer.parseInt(), Double.parseDouble() when string format is invalid.
The correct order is try block executes first, then catch block (if exception occurs), and finally block always executes at the end.
public class Test {
public static void main(String[] args) {
try {
int[] arr = {1, 2};
System.out.println(arr[5]);
} catch (Exception e) {
System.out.println("Caught");
}
}
}
ArrayIndexOutOfBoundsException is caught by the generic Exception catch block, printing 'Caught'.