Entrance Exams
Govt. Exams
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).
try {
throw new Exception("Test");
} catch(Exception e) {
System.out.println("Caught");
throw new RuntimeException("New");
} finally {
System.out.println("Finally");
}
The finally block executes after catch block. 'Caught' is printed, then finally block prints 'Finally', and then RuntimeException is thrown.
Java 7 introduced multi-catch using the pipe (|) operator: catch(IOException | SQLException e). This allows handling multiple exception types in one block.
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.
AutoCloseable (Java 7+) is the primary interface for try-with-resources. Closeable extends AutoCloseable. Both work with try-with-resources.
System.exit() terminates the JVM immediately. The finally block does not execute as the program terminates before reaching it.
Proper cause chaining calls super(msg, cause) in constructor, leveraging Exception's constructor that accepts both message and cause.
StackOverflowError occurs from stack overflow due to excessive method calls. Local variables contribute to stack but won't cause overflow like recursion.