In this article we will understand the differences between Checked and Unchecked Exceptions in Java language.Exception handling is essential to make a robust application, because the user does not want to see a stacktrace on your screen, but a well-written message indicating that only an error occurred. All the applications are subject to failures, and because of that, application will also need treatment of these failures.
The objective of this article is to show a little more about exception handling in Java , and specifically to illustrate the difference between Checked and Unchecked exceptions.Moreover, exceptions are one of the favorite topic discussed in the java interviews.We have covered few basic articles on exception handling in the previous years, this post will be a refreshment for the new Java folks.
Checked and Unchecked Exceptions
Many a times a developer is in dilemma to understand what a checked and unchecked exception is? When to make an exception checked or unchecked? All these questions will be answered in the subsequent sections.
To describe briefly Checked exceptions are those, which you are required to treat. It is with a try-catch block or a throws (releasing the same to another location). On the other hand, when you have the type Unchecked exceptions, then it need not be treated, you can treat only if you want or feel that it is necessary for the proper operation of your application.
Checked exceptions are used for recoverable errors, while Unchecked exceptions are used for unrecoverable errors. This means that when you know that your error can be treated, you can use Checked Exceptions, otherwise use Unchecked Exceptions.
To illustrate this, imagine that you have to create a Exception called “LowestPayementValueThanShipmentRateException”, this means that when the payment amount is less than the shipping rate, you will throw an Exception and deal with the way you want. For example: Asking the user to increase payment amount. These are Checked Exceptions, you know that the error may occur and know how to fix it if it occurs.
On the other hand, imagine a NullPointerException unexpected in its application. This error can not be handled, when error occurs, you should show only a message by telling the user that the error has occurred. But nothing can be done to fix it, if not restart the whole process. These Unchecked Exceptions inherit RuntimeException, hence these exceptions occur at runtime and not at design time. When you create a block of a code that requires you to use try-catch or throws, it will be for a typical Checked Exception. Unlike Runtime Exceptions which only occur at runtime and are unexpected.
Problems in Exception Handling
Problems occurs in some cases that this pattern is not well applied, such as JDBC API. See Listing 1 in the misuse of this pattern:
Exception Handling Example Listing 1 : using JDBC exceptions
try { PreparedStatement stmt = con.prepareStatement (query); / / ... } Catch (SQLException e) { throw new DataAccessException ("Problem in creating the Statement", e); }
You should be familiar with using the try-catch or throws using the JDBC API, treating a SQLException. But if you think about it, the SQLException is an exception too generic and most often is unrecoverable. Imagine for example, if your database crashed, then how will you recover it? There is no way, you can only show a message to the user.
In Listing 1, we transform the “alleged” SQLException Checked as Unchecked Exception by DataAccessException that only returns a message with the error and nothing can be done. Get used to this lack of standardization, because you can find many codes applied in place of Checked and Unchecked vice versa, but knowing the concept of both, you can easily make necessary changes.
Practical Example
To understand this concept better, let us apply the concepts in a practical example, where we have the following situation: Our method attempts to write a file in a folder A, but if some error occurs an IOException (Checked Exception) is thrown and we will try to write in an Alternative folder. Why is that? Imagine that a folder in the user’s computer may be without WRITE permission, and hence not to lose the file we will write to an alternative folder that has write permissions. After we get all the files that were in the alternate folder and put them in folder A manually, but not loosing the processing.
In Listing 2 you will see the code of the case described above.
Exception Handling Example Listing 2 : Example of a real Checked Exception
private static void createFiles(String alternatePath) { File file = null; try { SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy"); if (alternatePath.equals("")) file = new File("/home/manisha/javabeatdocs/file_" + fmt.format(new Date())); else file = new File(alternatePath + "file_" + fmt.format(new Date())); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write("Line 001"); writer.close(); } catch (IOException e) { if (file != null) { if (file.exists()) { file.delete(); createFiles("/home/manisha/alternatePath/"); } } } }
We can even improve a bit by putting one generic Exception in the code above. So anything that was not an IOException we could treat it as an Unchecked Exception, it would be an unrecoverable error and nothing we could do.
Summary
It is possible that many professionals do not know the real use of the concept described in this article, because a lot of times this goes unnoticed. But with the learning of this, it becomes much easier to understand the actual application (based on good programming practices) of exceptions.