Entrance Exams
Govt. Exams
int result = 0;
try {
result = 10 / 0;
} catch(Exception e) {
result = 20;
return result;
} finally {
result = 30;
}
System.out.println(result);
Return statement in catch block prepares the return value (20). Finally block executes but return happens after finally, so 20 is returned even though finally sets result to 30.
I. catch(FileNotFoundException e)
II. catch(IOException e)
III. catch(Exception e)
Catch blocks should be ordered from most specific to most general exception types. FileNotFoundException is more specific than IOException, which is more specific than Exception.
Exception class is the parent of all checked exceptions. RuntimeException extends Exception but is unchecked. Error and Throwable are higher in hierarchy.
try {
try {
throw new Exception("Inner");
} catch(Exception e) {
throw new RuntimeException("Outer");
}
} catch(RuntimeException e) {
System.out.println("Caught: " + e.getMessage());
}
The inner try catches Exception and throws RuntimeException. The outer catch catches RuntimeException and prints 'Caught: Outer'.
Try-with-resources automatically invokes close() on resources implementing AutoCloseable/Closeable. Syntax: try(Resource r = new Resource()) {...}
String str = "Java";
try {
int x = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid number");
} catch(Exception e) {
System.out.println("General exception");
}
Integer.parseInt("Java") throws NumberFormatException, which is caught by the first catch block. More specific exceptions should be caught before general ones.
The getCause() method returns the cause (underlying Throwable) of this Throwable. It's useful for exception chaining.
Comparing with null using == operator doesn't throw NPE. The other options call methods or unbox null values, which causes NullPointerException.
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
Accessing arr[5] when array has only 3 elements throws ArrayIndexOutOfBoundsException which is caught and 'Exception caught' is printed.
class MyException extends Exception {}
class MyRuntimeException extends RuntimeException {}
RuntimeException and its subclasses are unchecked, so they don't need to be caught or declared. Option A requires try-catch since MyException is checked.