Checked Exceptions vs Unchecked Exceptions
Learn the difference between checked and unchecked exceptions and understand their pros and cons
There are two types of exceptions:
- Checked exceptions: the compiler forces you to catch them
- Unchecked exceptions: you are free to catch them or not
Checked Exceptions
How does the compiler force you to handle checked exceptions?
Code Example
Because Kotlin has no checked exceptions, we will use Java to demonstrate the behavior. A function signature can indicate exceptions that it may throw:
class CheckedExceptions {static String readFile(String path) throws IOException {return Files.readString(Paths.get(path));}public static void main(String[] args) {try {System.out.println(readFile("secrets.txt"));} catch (IOException e) {// Handle exception properly...}}}
Here, the function signature of readFile
indicates that it may throw an IOException
– a checked exception in Java.
So when you call it, Java will force you to either:
- Wrap the call in a
try
-block which has acatch
-block that can handle aIOException
. - Or add a
throws
declaration to the function that callsreadFile
. Then this same procedure applies again to that function.
Pros of Checked Exceptions
Checked exceptions are intended to make the code more robust and safe.
A checked exception will always be handled. This means it cannot bubble up to the top of the call stack and cause the program to crash so easily.
Cons of Checked Exceptions
The major drawback of checked exceptions is that they distract developers from the actual logic. Oftentimes, the obligation to handle so many different exceptions makes developers simply swallow exceptions.
Of course, this is bad practice because it hides ...