Exception handling is a crucial part of writing robust Java applications. It helps you manage runtime errors gracefully, improving application stability and user experience. In this article, we’ll break down Java’s exception mechanism, types of exceptions, and best practices.
1. What Is an Exception?
An exception is an event that disrupts the normal flow of a program. In Java, exceptions are objects that represent an error or unexpected behavior.
2. Exception Hierarchy
php
java.lang.Object
└── java.lang.Throwable
├── Error (e.g., OutOfMemoryError)
└── Exception
├── Checked Exception (e.g., IOException)
└── Unchecked Exception (e.g., NullPointerException)
- Errors: Critical issues that applications shouldn’t try to handle.
- Checked Exceptions: Must be handled or declared (e.g.,
FileNotFoundException
). - Unchecked Exceptions: Don’t need to be declared (e.g.,
IllegalArgumentException
).
3. Basic Exception Handling Syntax
java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This will always execute");
}
4. Throwing Exceptions
Use throw
to manually throw an exception:
java
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
Declare exceptions using throws
:
java
public void readFile() throws IOException {
// file reading logic
}
5. Creating Custom Exceptions
java
public class InvalidUserException extends Exception {
public InvalidUserException(String message) {
super(message);
}
}
Usage:
java
if (!user.isValid()) {
throw new InvalidUserException("User is not valid");
}
6. Multi-Catch and Nested Exceptions
Java supports catching multiple exceptions in one block:
java
try {
// risky code
} catch (IOException | SQLException e) {
e.printStackTrace();
}
Nested exceptions (chained):
java
throw new RuntimeException("Top-level error", originalException);
7. Best Practices
- Catch only those exceptions you can handle.
- Don’t use exceptions for flow control.
- Always clean up in
finally
or use try-with-resources:
java
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// read file
}
- Log exceptions properly (use
logger.error(e.getMessage(), e)
). - Preserve the cause when wrapping exceptions.
8. Common Mistakes to Avoid
- Catching generic
Exception
or Throwable
. - Swallowing exceptions silently.
- Using too many nested
try-catch
blocks. - Not releasing resources (memory leaks, file locks).
Java's structured exception handling system provides a powerful way to detect, manage, and recover from errors. By following best practices and understanding exception types, you can build more resilient applications.