The difference between the checked and the unchecked exceptions in Java is a rule about the compiler, and not about the severity. The checked exceptions must be declared with throws or handled with catch. The unchecked exceptions, which are everything under RuntimeException, need neither, because the compiler assumes that they signal a mistake in your code rather than a failure in the outside world.
The previous lesson in this module covered "How Do try, catch and finally Cooperate?", and the next lesson in this module is about "How Does try-with-resources Close Things for You?".
What is the rule, exactly?
When the compiler checks a catch clause, it asks one question. Could this try block throw that type of exception? If the answer is yes, then the catch clause is allowed. If the answer is no, then the clause is a compile error.
For the unchecked exceptions the answer is always yes, because they can be thrown anywhere. For the checked exceptions the answer depends on whether the code inside the try block can actually produce one.
| Checked | Unchecked | |
|---|---|---|
| Where they live | directly under Exception | under RuntimeException |
| Compiler help | must be declared or caught | no declaration needed |
| Typical cause | an outside system: file, network, database | your own logic: null, bad index, bad argument |
| Good reaction | retry, fall back, ask the user | fix the code that produced it |
| Examples | IOException, SQLException, CloneNotSupportedException | NullPointerException, ArithmeticException, IllegalArgumentException |
The philosophy behind the split is worth understanding, because it explains why the rule feels arbitrary otherwise. If a failure comes from outside your program, then the caller might have a better idea than you do. A different file, a retry, a different provider. So the language makes you think about it at every call site. If the failure comes from your own logic, then there is nothing that the caller can do differently, so forcing a catch clause on every caller would be noise.
What happens when an unchecked exception escapes?
Nothing catches it, the runtime prints the stack trace, and the program ends. Here is a division method with no throws clause and no try block at all. It compiles without complaint.
public class UncheckedDemo {
static int divide(int a, int b) {
return a / b;
}
public static void main(String[] args) {
System.out.println(divide(10, 2));
System.out.println(divide(10, 0));
System.out.println("this line is never reached");
}
}The output is this.
5
Exception in thread "main" java.lang.ArithmeticException: / by zero
at UncheckedDemo.divide(UncheckedDemo.java:3)
at UncheckedDemo.main(UncheckedDemo.java:8)Only the first line of the output is from your code. The exception name, its message, and the frames tell you that the value of the divisor was zero and exactly which call produced it. No throws declaration appears anywhere, because none is needed.
How do you declare and handle a checked exception?
There are two options, and they mean different things. Handling it with catch means that you take the responsibility for it here and now. Declaring it with throws means that you pass the responsibility to your caller, who must then handle it or declare it again.
import java.io.IOException;
public class CheckedDemo {
static void loadSettings() throws IOException {
throw new IOException("settings.properties not found");
}
public static void main(String[] args) {
try {
loadSettings();
} catch (IOException e) {
System.out.println("handled IOException: " + e.getMessage());
}
}
}The output is this.
handled IOException: settings.properties not foundThe word throws in a method signature is a promise to the caller and not a piece of machinery. Nothing is caught automatically, no stack frame is created, and the exception behaves exactly as it would without the clause. The only effect is on the compiler, which now refuses to let anybody call that method without handling the possibility or passing it on.
Can a single catch clause handle both families?
It can, and you will do it in real code. Catching Exception covers the checked and the unchecked alike, which is exactly what you want in a boundary layer that logs the failures and converts them into something that the caller can handle.
public class CatchAnyDemo {
static void mayThrow(boolean checked) throws Exception {
if (checked) {
throw new java.io.IOException("network timeout");
}
throw new NullPointerException("reply was null");
}
public static void main(String[] args) {
for (boolean flag : new boolean[] { true, false }) {
try {
mayThrow(flag);
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
}The output is this.
IOException: network timeout
NullPointerException: reply was nullThe catch clause matches on the type, so one catch block for Exception handled both of them. If you need to treat them differently, then check the run-time type with instanceof inside the block, or write separate clauses with the more specific one first.
What if you catch something that can never be thrown?
The compiler stops you, which is a good sign that the check is doing something useful. Here is a try block that contains nothing but an integer assignment, with a catch clause for IOException.
error: exception IOException is never thrown in body of corresponding try statementThe same rule applies to a method that declares throws IOException but never throws it. The compiler treats a needless declaration as an error, so you cannot quietly hand the callers a promise that you do not intend to keep.
How do you add the context without losing the original failure?
When a low-level failure passes through a layer that knows more about the business, you wrap it in a new exception and you pass the original along as the cause. The original stack trace is then printed underneath the new one, so nothing is lost.
public class RethrowDemo {
static void readRow() throws Exception {
throw new Exception("database connection reset");
}
public static void main(String[] args) {
try {
readRow();
} catch (Exception e) {
System.out.println("logging: " + e.getMessage());
throw new IllegalStateException("could not import row", e);
}
}
}The output is this.
logging: database connection reset
Exception in thread "main" java.lang.IllegalStateException: could not import row
at RethrowDemo.main(RethrowDemo.java:11)
Caused by: java.lang.Exception: database connection reset
at RethrowDemo.readRow(RethrowDemo.java:3)
at RethrowDemo.main(RethrowDemo.java:8)The section that starts with Caused by: is the original failure and its original stack, and the two constructors of IllegalStateException made it possible. Passing the cause as the second argument is what preserves the trail. Throwing a new exception without it produces a report that stops at the wrapper and hides the real fault.
Rules worth memorising
- Unchecked means that it is under RuntimeException, and not that it is less serious.
- The checked exceptions must be caught or declared, and the compiler proves that you did it.
- A throws clause documents the intent and it satisfies the compiler. It does not handle anything.
- The unchecked exceptions almost always point at a bug, so you should fix the cause rather than catching and ignoring.
- When you wrap a failure, always pass the original along as the cause.
Try it yourself: write a method readScore(String text) that parses an integer and that declares throws NumberFormatException. Then delete that declaration and watch what the compiler says when you call it from main without a try block. Next, add a try block that catches NumberFormatException and prints the bad input, and confirm that the program compiles. Finally, catch IOException in a try block that cannot possibly throw it and note the exact compiler message.