Checked or Unchecked Exceptions?

1. Overview

In Java, there are basically two types of exceptions: Checked exceptions and Unchecked exceptions (RuntimeException and Error). The differences between checked, unchecked and error are:

Checked Exceptions must be explicitly caught or propagated. Unchecked exceptions do not have this requirement. They don’t have to be caught or declared thrown.

Checked Exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

Error is an exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

2. Checked Exception Example

Lets see the code snippets for Checked and Unchecked Exceptions here:

2.1 Create the Checked Exceptions

2.2 Create the method which throws Checked Exception and another method that calls it

Here readDataFromURL is the method which throws Checked Exception BadURLException and saveDataFromURL is the caller method. To call readDataFromURL it has only two choices. Either it catches the BadURLException or propagates to the call stack.

ThesaveDataFromURL showed below catches the exception.

To propagate the exception, change the saveDataFromURL as below

3. Unchecked Exception Example

3.1 Create the Unchecked Exception

3.2 Create the method which throw RuntimeException

Notice here, readDataFromURL is not throwing BadURLException. The saveDataFromURL method doesn’t have to catch theBadURLException either.

The saveDataFromURL method is free from catching the exception (can still choose to catch the exception, but optional) and propagating the exception.

3. Conclusion

In this post, we had a quick look on  Checked and Unchecked exception. Checked Exceptions must be explicitly caught or propagated. Unchecked exceptions do not have this requirement. Which one to choose is the depends on project requirements. But as per Joshua Bloch (Effective Java, item 41: Avoid unnecessary use of checked exceptions)

References

  1. Exceptions
  2. Effective Java
harinathk
 

Click Here to Leave a Comment Below 0 comments