Understanding Java Errors vs Exceptions: When to Catch and When Not To
The article explains the difference between Java's Error and Exception classes, clarifies which are recoverable, distinguishes checked and unchecked exceptions, and provides code examples showing how to declare, catch, and handle these exceptions in practice.
In Java, both Error and Exception are subclasses of Throwable. Errors represent serious problems that the application cannot reasonably recover from, such as OutOfMemoryError. When an Error occurs, the JVM typically terminates the program, and developers normally do not attempt to catch it.
Exceptions denote conditions that a program can anticipate and possibly recover from, such as invalid input or network failures. Exceptions are further divided into checked and unchecked categories.
Checked Exceptions
Checked exceptions must be either caught or declared in the method’s throws clause; the compiler enforces this requirement. A common example is IOException. The following method demonstrates declaring a checked exception:
public void readFile() throws IOException {
FileReader file = new FileReader("somefile.txt");
BufferedReader fileInput = new BufferedReader(file);
// ... read data
}If a method calls readFile(), it must either handle the IOException with a try‑catch block or propagate it further.
Unchecked (Runtime) Exceptions
Unchecked exceptions, also known as runtime exceptions, are not required to be declared or caught. The compiler does not enforce handling for them. Typical examples include NullPointerException, ArrayIndexOutOfBoundsException, and ClassCastException.
public class NullPointerExample {
public static void main(String[] args) {
String text = null;
try {
int length = text.length(); // throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
}
}Although unchecked exceptions do not need to be declared, writing robust code often involves anticipating them—especially NullPointerException —and handling them appropriately.
The article also includes two diagrams illustrating the hierarchy of Error vs Exception and the distinction between checked (red) and unchecked (green) exceptions.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
