There has been a long-standing debate in the Java language about checked versus unchecked exceptions. Here is the difference and why it’s important.
Join the DZone community and get the full member experience. Since the invention of the Java language, there has been a long-standing debate about checked versus unchecked/runtime exceptions. Some people argue that checked exceptions promote a better design. Others feel that checked exceptions get in the way, especially as systems mature and refactor over time, and therefore unchecked exceptions are better. The Effective Java Exceptions article, settles this debate once and for all: both checked and unchecked exceptions are acceptable, and each has its purpose within an application. I highly recommend reading that article. I will refer back to its concepts and terminology going forward. Exception handling is an important part of the design and architecture of an application. It represents alternate flows or scenarios other than the “happy path” flow through an application. Generally, business requirements only tell you how the application should behave when everything happens as expected. They rarely describe what to do when something goes wrong. Java got it right conceptually by allowing for both checked and unchecked exceptions. The problem is that developers have been taught poorly, or not taught at all, how to use one over the other properly. Even examples within the language itself are poorly designed and flawed. Think about classes in the java.sql or java.io packages. The majority of methods in classes in those packages throw SQLException or IOException that the caller must catch and handle. Other languages, such as Ruby, Kotlin, Scala, and Groovy, as well as other Java frameworks, such as Spring, swung the pendulum to the opposite side of the spectrum because of this. These languages don’t have the concept of checked exceptions and Spring Framework treats most things as unchecked. This mentality leaves things up to the developer building the application to know what exceptions to catch in certain situations. The article mentioned above introduces two main concepts: contingencies and faults. Table 1 defines these concepts and is taken from the article. Table 1: Contingencies and Faults Let’s show an example using this information: I want to transfer money from one account to another. Somewhere in my application, I have a method called transferFunds. This method needs three pieces of information: What are some possible outcomes that could happen during this transaction? Outcome #1 is the “happy path” flow through the transfer funds operation, so there isn’t any exception handling to be done.