Sub topic 3
Checked vs Unchecked Exceptions
Java sorts exceptions into two groups. The groups follow different rules, and the compiler enforces those rules before your program ever runs. This chapter explains the two groups, shows how to tell which group an exception belongs to, and covers the edge cases that confuse beginners.
Two Kinds of Exceptions
A checked exception is an exception that the compiler checks for. If a method you call can throw one, you must deal with it in your code. If you don't, your program will not compile.
An unchecked exception is an exception the compiler does not check for. You may handle it if you want, but the compiler will not force you to.
The compiler is the tool (javac) that turns your .java source file into a .class file the Java Virtual Machine can run. So checked exceptions are enforced at compile time. Unchecked exceptions only show up when the program runs.
The Rule: Catch or Declare
For checked exceptions, Java has one rule, often called catch or declare. When your code calls something that can throw a checked exception, you must do one of two things:
- Catch it. Put the call inside a
tryblock with a matchingcatchblock. - Declare it. Add a
throwsclause to your method's header. Athrowsclause is a list of exceptions that a method warns it might pass on to whoever called it.
Later chapters cover try/catch and throws in detail. For now you only need to know that one of the two is required.
Here is a program that breaks the rule. Thread.sleep pauses the program, and it can throw InterruptedException, which is checked.
public class SleepBroken {
public static void main(String[] args) {
System.out.println("Waiting...");
Thread.sleep(500);
System.out.println("Done");
}
}This file does not compile. javac reports:
SleepBroken.java:4: error: unreported exception InterruptedException; must be caught or declared to be thrown
Thread.sleep(500);
^
1 errorThe message says exactly what the rule says: "must be caught or declared to be thrown." Here is the fixed version, which declares the exception:
public class SleepDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("Waiting...");
Thread.sleep(500);
System.out.println("Done");
}
}It compiles and prints Waiting..., pauses for half a second, then prints Done.
Unchecked Exceptions Need Nothing
Now look at a program that can fail with an unchecked exception:
public class IndexDemo {
public static void main(String[] args) {
int[] scores = {90, 85, 70};
System.out.println("First: " + scores[0]);
System.out.println("Fourth: " + scores[3]);
System.out.println("This line never runs");
}
}This compiles with no errors. The compiler does not complain about scores[3], even though the array only has indexes 0, 1, and 2. When you run it, it prints First: 90 and then crashes with ArrayIndexOutOfBoundsException. That exception is unchecked, so Java let the mistake through to run time.
How to Tell Which Is Which
The group an exception belongs to depends only on where it sits in the class family tree you saw in the previous chapter:
- If the class is
RuntimeExceptionor extends it, it is unchecked. - If the class is
Erroror extends it, it is unchecked. - Every other subclass of
Throwableis checked. That includesExceptionitself andThrowableitself.
The table below lists common examples.
| Exception | Group | Typical cause |
|---|---|---|
| `IOException` | Checked | Reading or writing a file or network stream failed |
| `FileNotFoundException` | Checked | A file you tried to open does not exist |
| `InterruptedException` | Checked | Another thread interrupted a waiting thread |
| `ClassNotFoundException` | Checked | A class loaded by name could not be found |
| `NullPointerException` | Unchecked | You used a variable that holds `null` |
| `ArithmeticException` | Unchecked | Integer division by zero |
| `IllegalArgumentException` | Unchecked | A method got a bad argument |
| `NumberFormatException` | Unchecked | `Integer.parseInt` got text that is not a number |
| `ArrayIndexOutOfBoundsException` | Unchecked | An array index was too big or negative |
| `OutOfMemoryError` | Unchecked (an Error) | The JVM ran out of memory |
You can also ask Java directly. The method isAssignableFrom tells you whether one class is the same as, or a parent of, another class. This program uses it to sort exceptions into the two groups:
import java.io.FileNotFoundException;
import java.io.IOException;
public class Classify {
static String kind(Class<?> type) {
if (RuntimeException.class.isAssignableFrom(type)
|| Error.class.isAssignableFrom(type)) {
return "unchecked";
}
return "checked";
}
public static void main(String[] args) {
System.out.println("IOException: " + kind(IOException.class));
System.out.println("FileNotFoundException: " + kind(FileNotFoundException.class));
System.out.println("NumberFormatException: " + kind(NumberFormatException.class));
System.out.println("OutOfMemoryError: " + kind(OutOfMemoryError.class));
System.out.println("Exception: " + kind(Exception.class));
}
}Output:
IOException: checked
FileNotFoundException: checked
NumberFormatException: unchecked
OutOfMemoryError: unchecked
Exception: checkedWhy Java Has Two Groups
The split reflects two different kinds of problems.
Checked exceptions are for problems outside your control that a careful program should expect. A file might be missing. A network might drop. A user might delete a folder. Your code can be perfect and these still happen. Java forces you to think about them so you can plan a response, such as showing a message or trying again.
Unchecked exceptions usually mean a bug in the code. Dividing by zero, using null, and reading past the end of an array are mistakes you fix by changing the code. If Java made you catch every possible NullPointerException, almost every line would need a try block. So the compiler leaves these alone.
Errors are serious problems in the JVM itself, such as running out of memory. A normal program cannot fix them, so Java does not ask you to handle them.
Edge Cases That Trip Beginners
You can still catch unchecked exceptions
"Unchecked" does not mean "uncatchable." The catch (NumberFormatException e) example in the first chapter caught an unchecked exception. The compiler just doesn't require it.
Catching a checked exception that cannot happen is an error
The compiler also checks the opposite direction. If you catch a checked exception that nothing in the try block can throw, compilation fails:
error: exception IOException is never thrown in body of corresponding try statementThis rule does not apply to Exception or Throwable, because those also cover unchecked exceptions, which can come from anywhere.
Subclasses follow their parent
FileNotFoundException extends IOException, so it is checked too. NumberFormatException extends IllegalArgumentException, which extends RuntimeException, so it is unchecked. You only need to find the nearest of RuntimeException, Error, or Throwable above it.
Lambdas and overridden methods
Some methods cannot add checked exceptions. When you override a method, the new version cannot declare checked exceptions that the original method did not declare. Lambdas follow the same rule. A Runnable lambda cannot throw InterruptedException, because Runnable.run() declares no checked exceptions. In these places you must catch the checked exception inside the method body.
Exercises
Exercise
Is java.io.UncheckedIOException checked or unchecked? Its parent class is RuntimeException.
Show answer
Unchecked. It extends RuntimeException, and anything under RuntimeException is unchecked, even though its name contains "IO".
Exercise
A method calls Files.readString(path), which can throw IOException. The method has no try block and no throws clause. What happens when you compile it, and what are the two ways to fix it?
Show answer
Compilation fails with "unreported exception IOException; must be caught or declared to be thrown". Fix it by wrapping the call in try with a catch (IOException e) block, or by adding "throws IOException" to the method header.
Exercise
Integer.parseInt("abc") throws NumberFormatException. Why does code that calls Integer.parseInt compile without any try block or throws clause?
Show answer
NumberFormatException extends IllegalArgumentException, which extends RuntimeException, so it is unchecked. The compiler does not require unchecked exceptions to be caught or declared.
Exercise
Is a class declared as "class ConfigMissingException extends Exception" checked or unchecked? What would you change to make it unchecked?
Show answer
It is checked, because it extends Exception and not RuntimeException. To make it unchecked, change it to extend RuntimeException.