Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.
Get Avnee Akkewar’s stories in your inbox
Join Medium for free to get updates from this writer.
It allows you to catch and process exceptions (unexpected or exceptional conditions) that occur during program execution.
Exception Hierarchy
In Java, all exception classes are derived from java.lang.Throwable. The Throwable class has two direct subclasses:
- Error: Represents serious problems that applications should not try to catch (e.g.,
OutOfMemoryError). - Exception: Represents conditions that applications might want to catch (e.g.,
IOException).
Exceptions are further divided into two categories:
- Checked Exceptions: These are exceptions that are checked at compile-time. For example,
FileNotFoundException,IOException. Methods that might throw checked exceptions must declare them using thethrowskeyword. - Unchecked Exceptions (Runtime Exceptions): These are exceptions that are checked at runtime. For example,
ArithmeticException,NullPointerException. They are subclasses ofRuntimeException.
Try-Catch-Finally Blocks
The try block contains code that might throw an exception. The catch block handles the exception, and the finally block contains code that executes regardless of whether an exception occurred.
try {
// Code that may throw an exception
} catch (ExceptionType name) {
// Code to handle the exception
} finally {
// Code that will always execute
}Throwing Exceptions
You can use the throw keyword to explicitly throw an exception.
public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
}Example with Detailed Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("An error occurred while closing the file: " + e.getMessage());
}
}
}
}




