What is the difference between a checked and an unchecked exception in Java, and how does the compiler treat them?
There are two kinds of exception, and the difference between them is really about who decides that the failure should be handled.
A checked exception is one that the compiler makes you deal with. If your code might throw one, you have to either catch it or say that you are throwing it onwards in the signature of your method. If you do neither, the code does not compile.
An unchecked exception is one that the compiler leaves alone. Every subclass of RuntimeException is unchecked, and so is every subclass of Error. You may catch them if you want to, but nobody makes you.
So what decides which kind an exception is? It is not about how serious it is. It is about whether the failure is inside your program or outside it.
A checked exception almost always comes from something outside your program. A file that cannot be read, a network call that fails, a database that is not answering. The caller is in a position to do something about it, so the language makes them think about it.
An unchecked exception almost always means a mistake in your program. A null pointer, an index that is out of range, an argument that is not allowed. No amount of catching will fix those, so making everybody write a catch block would only fill the code with noise.
public class Main {
public static void main(String[] args) {
try {
// An unchecked exception. Nothing forces you to catch this.
throw new IllegalArgumentException("not a valid value");
} catch (IllegalArgumentException e) {
System.out.println("caught : " + e.getMessage());
}
try {
// A checked exception. The compiler will not let this through.
throw new java.io.IOException("the file could not be read");
} catch (java.io.IOException e) {
System.out.println("caught : " + e.getMessage());
}
}
}
The next question in this topic looks at when you should throw each kind.