The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › Exceptions
Checked and unchecked exceptions
Why do some exceptions keep the code from even compiling unless you handle them?
Why it exists — If the fact that a method can fail is written only in the documentation, the caller easily forgets the cases where the file is missing or the connection is lost. Java's checked exceptions make you write such failures in the throws of the method declaration, and the compiler tells you if the caller does not handle them. Mistakes that require fixing the code (a null reference, a wrong argument) are left as unchecked exceptions, so the code does not force handling at every call.
Where it's used today — You meet them in standard APIs that fail because of circumstances outside the program, such as IOException (file and network input and output) and SQLException (calling the database through JDBC). Spring's JdbcTemplate converts SQLException into the DataAccessException family of unchecked exceptions, so that throws does not spread through service code. If there is nothing to do at that point, you wrap the original exception as the cause and throw it as an unchecked exception.
Java exceptions fall into two groups. With a checked exception (such as IOException), the compiler refuses to compile the code unless you catch the exception (try-catch) or declare that it is thrown (throws). An unchecked exception (typically RuntimeException or one of its subclasses) has no such requirement, so the code compiles with no handling at all.
Checked against real execution · All 24 combinations were actually compiled and run on JDK 21 and checked against the results
Concepts in this lab
- Checked and unchecked exceptions
- Unchecked exceptions are RuntimeException and its subclasses (in the specification, the Error classes are also unchecked), and the compiler does not check whether they are handled (examples are NullPointerException and IllegalArgumentException). Checked exceptions are all other Exception classes, and the code compiles only if they are handled with catch or declared with throws (examples are IOException and SQLException). By default, Spring's @Transactional rolls back only on RuntimeException and Error, and commits on checked exceptions.
- Exception and Error
- Both are subtypes of Throwable that represent abnormal situations while a program runs. An Exception is a situation that the application can catch and handle (such as invalid input or a missing file). An Error is a serious problem at the JVM level, such as running out of memory or a stack overflow, and applications usually do not try to recover from it.
- throws clause
- Why it exists — If there were no way to pass a checked exception outward, even a method with nothing to do about it at that spot would be forced to catch it, and it would be easy to hide the error with an empty catch. A throws clause defers handling to the caller, so that the exception is caught in code that can handle it appropriately.
- Where it's used today — You often see throws IOException in the declarations of standard APIs that handle files and networks, such as Files.readString. JUnit test methods are sometimes given throws Exception so that a checked exception raised during a test is not caught but shows up as a test failure.
- This is the syntax, written at the end of a method declaration as in throws IOException, that announces that the method can throw that exception to its caller. You must write it if you do not catch a checked exception inside the method, and the code then compiles only if the caller of that method in turn catches the exception or declares it with throws. It does not handle the exception. It passes the obligation to handle it on to the caller. For an unchecked exception you do not have to write it, and even if you do, it creates no obligation for the caller. It is a different word from throw, the statement that actually throws an exception.
- Wrapped exception
- Why it exists — If you throw a low-level exception upward as it is, the upper code is also tied to the exception of a technical detail such as SQLException, and for a checked exception, throws is added to every method it passes through. Wrapping an exception turns it into an exception that fits that layer while keeping the original exception as the cause, so the first cause is not lost.
- Where it's used today — It is used to wrap an IOException in an UncheckedIOException and throw it in a place where a checked exception cannot be thrown, such as a lambda passed to Stream's map. Spring also wraps JDBC's SQLException in exceptions of the DataAccessException family and passes it on.
- This means creating a new exception of another kind that refers to the caught exception as its cause, and throwing the new one. It is called wrapping, but the original exception does not go inside the new one. The new exception only holds a reference to it. If you catch a checked exception and throw it again as an unchecked exception, as in throw new RuntimeException(e), the code compiles without a throws clause on every method that the exception passes through. When you pass the original exception to the constructor, the new exception refers to it as its cause, and it appears in the error output under Caused by. If you do not pass the original exception, there is no way to tell what went wrong in the first place, so always pass it. Wrapping does not make the exception go away, so if nothing catches it anywhere, execution stops.
Try these
- Default settings — A checked exception is thrown with no handling. The code does not compile.
- An unchecked exception just compiles — Only the exception changes in the same code. The code compiles, and the program stops at run time.
- Even when no exception is thrown — The code would not throw an exception if it ran, and yet it is a compile-time error.
- Adding only throws — The error does not go away. It moves to main, which calls read.
- throws all the way up to main — The code compiles, but nothing catches the exception, so the program stops.
- Catching in the caller — read announces that it throws, and main catches the exception and handles it.
- Wrapping in a RuntimeException — The code compiles without throws, but the exception has not gone away.
Running with the default settings
- The compiler checks the read method: It contains throw new IOException(...). IOException is a checked exception. A line that can throw a checked exception compiles only if it is enclosed in a try-catch or the declaration of its method has a throws clause.
- read has neither a try-catch nor a throws clause: This is a compile-time error. The compiler reports "unreported exception IOException; must be caught or declared to be thrown". In other words, the code can throw an IOException without saying so, and the exception must be either caught or declared as thrown.
- Compilation failed: No class file is produced, so the program cannot run. A problem that would occur at run time was stopped in advance, before the program ran.
Result of this run
- With a checked exception, the code compiles only if it does one of two things: "catch it, or declare that it is thrown". This mechanism keeps you from overlooking problems that arise from circumstances outside the program and that you can prepare for, such as a missing file or a dropped network connection.
Code
import java.io.IOException;
public class Main {
static String read(boolean missing) {
if (missing) throw new IOException("file not found");
return "content";
}
public static void main(String[] args) {
String s = read(true);
System.out.println("read: " + s);
System.out.println("end of main");
}
}
Assumptions of this model
All 24 combinations were actually compiled on JDK 21 in our test environment from the same source as the code on the screen, and those that compiled were run, and the compilation result, the line with the error, the compiler message, the output, the exit status, and the first line of standard error were checked against the results. The compiler messages are written in the form that the command-line javac shows (class names only). It was confirmed in the same way that throwing an Error with no handling also compiles and that throwing Exception itself is treated as a checked exception. The model covers only the case with two methods (read and main). The rule is the same when the calls go deeper: every method that a checked exception passes through must catch it or declare it. An uncaught exception ending the program applies to the case where main is the only thread.
Previous lab: Exceptions and finally · Next lab: Generics