Java Exception Handling Guide
Short answer: an exception is an object that signals an error during execution. In Java you handle it with try/catch/finally, pass it up with throws, and use try-with-resources to close files and connections safely.
try, catch, finally
try {
int[] arr = new int[3];
arr[5] = 10; // throws
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
tryholds code that might fail.catchhandles a specific exception type.finallyruns whether or not an exception occurred, which suits cleanup code.
The exception hierarchy
| Type | Examples | Must you handle it? |
|---|---|---|
Error | OutOfMemoryError, StackOverflowError | No; the JVM is in serious trouble |
Checked (Exception but not RuntimeException) | IOException, SQLException | Yes: catch it or declare it with throws |
Unchecked (RuntimeException) | NullPointerException, IllegalArgumentException | No; usually a programming bug |
All of them extend Throwable. The compiler forces you to deal with checked exceptions because they represent failures outside your program's control, such as a missing file.
throw vs throws
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}
public String read(String path) throws IOException {
return Files.readString(Path.of(path));
}
throwcreates and throws an exception at a specific point.throwsin a method signature warns callers that the method may throw a checked exception.
Multiple and multi-catch
try {
process();
} catch (IOException | SQLException e) {
log.error("Data access failed", e);
} catch (Exception e) {
log.error("Unexpected error", e);
}
Put more specific exceptions before general ones; otherwise the compiler reports an error.
try-with-resources
Anything that implements AutoCloseable is closed automatically, even when an exception occurs:
try (BufferedReader reader = Files.newBufferedReader(Path.of("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Read failed: " + e.getMessage());
}
This replaces long finally blocks that closed resources manually.
Custom exceptions
public class InsufficientFundsException extends Exception {
private final double shortfall;
public InsufficientFundsException(String message, double shortfall) {
super(message);
this.shortfall = shortfall;
}
public double getShortfall() { return shortfall; }
}
Extend Exception for recoverable, checked conditions and RuntimeException for programming errors or when you do not want to force callers to catch it.
Wrap and rethrow with the cause
try {
repository.save(user);
} catch (SQLException e) {
throw new UserServiceException("Could not save user", e);
}
Passing the original exception as the cause keeps the full stack trace for debugging.
Best practices
- Never swallow exceptions with an empty
catchblock. At least log them. - Catch the most specific type you can handle; avoid catching
Throwable. - Do not use exceptions for normal control flow. They are slow compared with a simple check.
- Add useful messages with the values involved, but never include passwords or personal data.
- Fail early: validate arguments at the start of a method.
- Clean up with try-with-resources rather than
finallywhen possible.
Reading a stack trace
Start at the top line: it names the exception type and message. The first frame below it that belongs to your own package is usually where to look. Lines starting with "Caused by" show the underlying reason.
Next steps
Learn data structures in the Collections Framework and functional processing in the Streams API. For object design see Java OOP concepts.
