Govt Exams
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.
The 'throws' keyword is used in method declaration to indicate that the method might throw checked exceptions. Syntax: method() throws ExceptionType {}
ArrayIndexOutOfBoundsException is thrown when trying to access an array element with an index that is out of the valid range (0 to length-1).
int x = 10;
try {
x = x / 0;
} catch (ArithmeticException e) {
x = 20;
} finally {
x = 30;
}
System.out.println(x);
The finally block always executes last and sets x to 30. The output will be 30 because finally block assignments override catch block assignments.
The finally block in Java always executes whether an exception is caught or not, except when System.exit() is called or JVM terminates abnormally.
Throwable is the superclass. Exception and Error are direct subclasses, and RuntimeException is a subclass of Exception.
printStackTrace() prints to System.err, while getStackTrace() returns an array of StackTraceElement objects. Both exist and serve different purposes.
public class Test {
public static void main(String[] args) {
try {
throw new Exception("Test");
} catch (Exception e) {
System.out.println("1");
} catch (Exception e) {
System.out.println("2");
}
}
}
Multiple catch blocks with the same exception type cause compilation error. Java doesn't allow duplicate catch blocks for identical exception types.
public class ExceptionTest {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught");
} finally {
System.out.println("Finally");
}
}
}
ArithmeticException is caught by the catch block printing 'Caught', then finally block executes printing 'Finally'.
The finally block always executes regardless of whether a return, break, continue, or exception occurs in try or catch blocks, unless System.exit() is called.