Java checked or unchecked better

Both Checked and unchecked exceptions raised at runtime not at compile time. Both checked and unchecked exception will terminate the application if we don’t handle them.

Checked exceptions are mandatory to handle or declare otherwise we will get compilation error. All over the code we write try-catch blocks and throws clauses to handle checked exceptions. But compiler won’t complain about unchecked exceptions even we don’t handle or declare. So I personally prefer unchecked exceptions as unchecked exceptions avoid try-catch and throws clauses all over the code.

I remember in old java projects around 60% of methods used to have try-catch blocks. For Example, We write a try-catch blocks in DAO methods to catch exceptions propagated from Database API’s(like JDBC). After catching exceptions in DAO method we may convert API specific exceptions into user defined exceptions and then rethrow them to service method. In service method we write try-catch blocks to catch the exceptions propagated from DAO method, Then we may convert DAO exceptions again into another user defined exception and rethrow them to controller. In controller method we write try-catch blocks to catch the exceptions propagated from service method. In controller catch blocks we may forward control to corresponding output page based on the type of exception as per the application requirements. By looking into this scenario, we could understand that we used to write lot of exception handling code all over the project due to checked exceptions. But if API’s declares unchecked exceptions we no need to write all these exception handling code.

Some times we required to use API’s which may throw only checked exceptions. In those scenario’s we have to handle them with try-catch block, In catch block we need to encapsulate those checked exceptions into user defined unchecked exceptions and rethrow them. This way we could avoid propagation of checked exceptions all over the call stack.

We have been discussing that, If we deal with only unchecked exceptions we could avoid exception handling code all over the application. So our application is clean. But as we don’t have exception handling code in our application, what happens if really unchecked exception raised in the execution of the application? Answer is application will get terminated. So we can’t completely avoid handling of unchecked exceptions. Some where we need to handle these exceptions.

Now a days all the technologies and frameworks provide a support of Centralized Exception Handling or Global Exception Handling mechanism. Using these concepts we handle exceptions in java projects in projects. So by using unchecked exceptions we could avoid handling code all over the application and we will handle them with Global exception handling in one place of the project.

Scroll to Top