Govt. Exams
Entrance Exams
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.
throws declaration indicates the method may throw IOException. The caller is responsible for handling it with try-catch or declaring throws. The method doesn't always throw it.
ArrayIndexOutOfBoundsException is thrown when attempting to access array elements with invalid indices. It's an unchecked exception extending RuntimeException.
Unchecked exceptions (RuntimeException subclasses) don't require explicit handling. If not caught, they propagate up the call stack, eventually terminating the thread if not caught anywhere.
NullPointerException is thrown when attempting to use an object reference that hasn't been instantiated. Java doesn't have NullArgumentException.
throw explicitly throws an exception object; throws declares in method signature that exceptions may be thrown. Example: throw new IOException() vs public void method() throws IOException.
The finally block executes unconditionally after try and/or catch blocks complete, making it ideal for resource cleanup. It runs even if try or catch blocks return.
Multiple exceptions are declared using comma-separated syntax in the throws clause. Parentheses and pipe operators are not valid syntax for this purpose.
SQLException is a checked exception that must be caught or declared. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are unchecked exceptions (RuntimeException subclasses).