Throwable Hierarchy
Explore the Java Throwable hierarchy to understand the distinctions between Errors, checked exceptions, and unchecked exceptions. Learn how this structure guides error handling, allowing you to anticipate, recover from, and fix different runtime issues. Gain insights into compiler rules and best practices for designing robust exception handling in Java applications.
Not all problems in Java are created equal. Some issues are catastrophic system failures that we can’t stop, while others are simple logic mistakes we should have avoided. Still, others are predictable external hiccups, like a missing file or a network timeout, that we must prepare for.
Java organizes all these scenarios into a strict family tree. Understanding this hierarchy allows us to write code that knows exactly which problems to anticipate, which to recover from, and which to fix.
The Throwable root
In Java, runtime failures that interrupt normal flow are represented as Throwable objects. These objects all share a single common ancestor: the java.lang.Throwable class.
Only objects that extend Throwable can be used with Java’s exception handling mechanisms (the throw keyword to trigger an error, or the catch keyword to handle it). While Throwable provides essential methods like getMessage() and printStackTrace(), we rarely use this class directly. Instead, we work with its two main subclasses: ...