Sub topic 2
The Exception Family Tree
In Java, every exception is an object. Each one is made from a class, and those classes are related to each other like members of a family. If you know the family tree, you can tell what kind of problem an exception describes and how your program is expected to deal with it.
This chapter walks through that tree from the top down.
Exceptions Are Objects
A class is a blueprint for making objects. An exception class is a class that describes one kind of problem. When something goes wrong, Java creates an object from the matching class and "throws" it.
For example, dividing an integer by zero creates an ArithmeticException object. That object carries information about the problem:
- A message, which is a short text explaining what went wrong. You read it with
getMessage(). - A stack trace, which is a record of which methods were running when the problem happened. A later chapter covers it.
- An optional cause, which is another exception that led to this one. A later chapter covers this too.
All exception objects have these parts because they share a common ancestor.
Inheritance in One Minute
Inheritance means one class is built on top of another. The new class is the subclass (the child). The class it builds on is the superclass (the parent). The child gets everything the parent has, and it can add more.
A child object also counts as its parent type. A Dog is also an Animal. In the same way, an ArithmeticException is also a RuntimeException, which is also an Exception, which is also a Throwable.
That "is also a" relationship matters a lot. When you later write code to catch an exception, catching a parent type also catches all of its children.
The Top of the Tree: Throwable
At the very top is Throwable. Throwable is the class that every throwable thing in Java comes from. Only objects of type Throwable (or its children) can be thrown and caught.
Throwable has two direct children:
ErrorException
Exception then has one especially important child, RuntimeException. These three branches are the main parts of the tree.
Branch 1: Error
An Error is a serious problem inside the Java Virtual Machine (JVM). The JVM is the program that runs your Java code. Errors usually mean the environment itself is broken, so the bug is not in one line of your logic.
Common examples:
OutOfMemoryError: the JVM has run out of memory for new objects.StackOverflowError: a method called itself too many times, usually through endless recursion.
Your program normally cannot fix these. If memory is gone, there is little useful work left to do. For this reason, ordinary code should not try to catch Error objects.
Branch 2: Exception
An Exception (with a capital E, meaning the class) is a problem that a well-written program might expect and recover from. The file you wanted to open is missing. The network connection dropped. The user typed bad data.
A common example is IOException, which stands for "input/output exception". It covers problems with reading or writing data, such as files. Its child FileNotFoundException covers one specific case: the file does not exist.
Many subclasses of Exception are checked exceptions. The compiler makes you deal with these before it will build your program. The next chapter explains exactly what that means.
Branch 3: RuntimeException
A RuntimeException is a child of Exception that usually signals a bug in the program's logic. Examples:
NullPointerException: you used a variable that points to no object (null).ArithmeticException: you divided an integer by zero.IllegalArgumentException: a method got a value it does not accept.NumberFormatException: a child ofIllegalArgumentException, thrown when text such as"42x"cannot become a number.ArrayIndexOutOfBoundsException: you asked for an array position that does not exist.
RuntimeException and all its children are unchecked exceptions. The compiler does not force you to handle them. Error and its children are also unchecked.
Comparing the Branches
| Branch | What it means | Should ordinary code catch it? | Examples |
|---|---|---|---|
| `Error` | The JVM or environment has a serious problem | No | `OutOfMemoryError`, `StackOverflowError` |
| `Exception` (not runtime) | An expected problem outside your control | Yes, when you can respond to it | `IOException`, `FileNotFoundException` |
| `RuntimeException` | Usually a bug in program logic | Sometimes, but fixing the bug is better | `NullPointerException`, `ArithmeticException` |
Seeing the Tree in Code
You can ask Java to show you the family line of any exception class. The method getSuperclass() returns a class's parent. This program follows parents upward until there are none left.
public class FamilyTree {
public static void main(String[] args) {
Class<?> c = NumberFormatException.class;
while (c != null) {
System.out.println(c.getName());
c = c.getSuperclass();
}
}
}Save it as FamilyTree.java, then compile and run it:
javac FamilyTree.java
java FamilyTreeThe output is:
java.lang.NumberFormatException
java.lang.IllegalArgumentException
java.lang.RuntimeException
java.lang.Exception
java.lang.Throwable
java.lang.ObjectThe last line is Object. Object is the parent of every class in Java, so the family tree actually sits on top of it. Change NumberFormatException to java.io.FileNotFoundException or StackOverflowError and run the program again to trace other branches.
Checking "Is Also A" with instanceof
The instanceof operator tests whether an object belongs to a type, including its parent types. This program shows the "is also a" rule in action.
public class IsAlsoA {
public static void main(String[] args) {
Throwable t = new ArithmeticException("divide by zero");
System.out.println("Message: " + t.getMessage());
System.out.println("ArithmeticException? " + (t instanceof ArithmeticException));
System.out.println("RuntimeException? " + (t instanceof RuntimeException));
System.out.println("Exception? " + (t instanceof Exception));
System.out.println("Throwable? " + (t instanceof Throwable));
System.out.println("Error? " + (t instanceof Error));
}
}The output is:
Message: divide by zero
ArithmeticException? true
RuntimeException? true
Exception? true
Throwable? true
Error? falseThe object counts as every type on its own line up the tree. It does not count as Error, because Error is on a different branch.
Note that this program only creates the exception object and never throws it. Creating an exception does nothing special on its own. It only changes program flow when it is thrown.
Edge Cases Worth Knowing
- Names can mislead. Most errors end in
Errorand most exceptions end inException, but this is only a naming habit. The real type comes from the class's parent, not its name. - Do not catch
Throwable. CatchingThrowablealso catches everyError, includingOutOfMemoryError. This can hide serious problems and leave your program running in a broken state. - Depth varies. Some exceptions sit just below
Exception. Others, likeFileNotFoundException, are several levels down. Catching a parent catches every level below it. - You can add to the tree. Later in this tutorial you will write your own exception classes. You pick a parent such as
ExceptionorRuntimeException, and that choice decides which branch your class joins.
Exercise
Is FileNotFoundException a RuntimeException? Trace its family line up to Throwable to explain your answer.
Show answer
No. FileNotFoundException's parent is IOException, IOException's parent is Exception, and Exception's parent is Throwable. RuntimeException is not on that line, so FileNotFoundException is not a RuntimeException.
Exercise
A program catches Exception. Will it catch a NullPointerException? Will it catch a StackOverflowError?
Show answer
It will catch NullPointerException, because NullPointerException is a child of RuntimeException, which is a child of Exception. It will not catch StackOverflowError, because StackOverflowError is on the Error branch, which does not sit under Exception.
Exercise
Why should ordinary code avoid catching Error objects such as OutOfMemoryError?
Show answer
An Error means the JVM or its environment has a serious problem, such as running out of memory. The program usually cannot fix it, and catching it can hide the problem and leave the program running in a broken state.