Exception Handling in Java: try, catch, finally
Introduction
Things go wrong at runtime: files go missing, input is invalid, networks fail. Java's exception handling lets you detect these problems and respond instead of crashing. This tutorial covers try/catch/finally, try-with-resources, and throwing exceptions yourself.
Prerequisites
- JDK installed
- Basic Java syntax and methods
Step-by-Step Guide
Step 1: Catch an exception with try/catch
Put risky code in a try block and handle the problem in a matching catch block. Catch the most specific exception type you can.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}Step 2: Run cleanup code with finally
Code in a finally block runs whether or not an exception occurred, which makes it useful for cleanup.
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index");
} finally {
System.out.println("This always runs");
}Step 3: Close resources with try-with-resources
Resources that implement AutoCloseable, such as readers and streams, are closed automatically when declared in the try parentheses. IOException is a checked exception, so you must catch it or declare it.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Could not read file: " + e.getMessage());
}Step 4: Throw your own exceptions
Use throw to signal invalid input or state. Choose an exception type that describes the problem.
public static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Age set to " + age);
}FAQs
- What is the difference between checked and unchecked exceptions?
- Checked exceptions (like IOException) must be caught or declared in the method signature. Unchecked exceptions (subclasses of RuntimeException, like NullPointerException) don't have to be, and usually indicate programming errors.
- Should I catch the generic Exception class?
- Usually not. Catching specific exceptions makes your intent clear and avoids hiding unrelated bugs. Reserve broad catches for top-level handlers that log and report.
Summary
Catch specific exceptions, clean up with finally or try-with-resources, and throw meaningful exceptions for invalid input. Handled well, errors become predictable instead of fatal.
Comments
Log in or create a free account to join the discussion.