Exception Handling
Expert Answer & Key Takeaways
Deep dive into Java's robust mechanism to handle runtime errors: try, catch, finally, throw, and throws keywords.
Exception Handling in Java
An Exception is an unwanted or unexpected event occurring during the execution of a program (at runtime) that disrupts the normal flow of instructions. Exception Handling is a powerful mechanism that handles these runtime errors so the normal flow of the application can be maintained.
1. Hierarchy of Java Exceptions
The
java.lang.Throwable class is the root class of Java Exception hierarchy. It has two main subclasses:- Error: Represents serious problems that a reasonable application should not try to catch (e.g.,
OutOfMemoryError,StackOverflowError,VirtualMachineError). They are unrecoverable. - Exception: Represents conditions that a reasonable application might want to catch and recover from.
1.1 Types of Exceptions
- Checked Exceptions (Compile-time Exceptions): Exceptions that are checked by the compiler at compile-time. If some code throws a checked exception, you must handle it using a
try-catchblock or declare it usingthrows, otherwise the program will not compile. (e.g.,IOException,SQLException). - Unchecked Exceptions (Runtime Exceptions): Exceptions that occur at the time of execution. The compiler does not force you to handle them. (e.g.,
ArithmeticException(divide by zero),NullPointerException,ArrayIndexOutOfBoundsException).
2. Java Exception Handling Keywords
Java uses 5 keywords to handle exceptions:
try, catch, finally, throw, and throws.2.1 The try-catch Block
tryblock: You put the risky code (code that might throw an exception) inside thetryblock. It must be followed by eithercatchorfinally.catchblock: Used to handle the exception thrown by thetryblock. You can use multiplecatchblocks to handle different types of exceptions differently.
try {
int data = 100 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}2.2 The finally Block
- The
finallyblock is used to execute crucial code such as closing connections, closing streams, etc. - Rule: The
finallyblock is ALWAYS executed whether an exception occurs or not, and whether it is handled or not.
try {
// Code that opens a file
} catch (Exception e) {
// Handle error
} finally {
// Close the file (executes guaranteed)
}2.3 The throw Keyword
The
throw keyword is used to explicitly throw a single exception from within a method or any block of code. You can use it to throw custom exceptions based on your logic.void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
}2.4 The throws Keyword
The
throws keyword is used in the method signature. It does not throw an exception itself; rather, it indicates to the caller of the method that "This method might throw these exceptions, so please handle them."void readFile() throws IOException {
// Code that reads a file and might throw IOException
}3. Important Rules
- When using multiple
catchblocks, the most specific exception type must come first, and the most generic (Exception) must come last. Otherwise, you get a compile-time error (unreachable code). - If a
tryblock is used, it MUST be followed by at least onecatchblock OR afinallyblock. A lonetryblock is a syntax error.
Course4All Editorial Board
Verified ExpertSubject Matter Experts
Comprising experienced educators and curriculum specialists dedicated to providing accurate, exam-aligned preparation material.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.