<div dir="ltr" style="text-align: justify;">Exception handling in a robust application is very important part. It is not part of functional requirement of any product but it is necessary to handle any ill condition like connection not available, resource not found, invalid input, null input and so on.</div>
<div dir="ltr"></div>
<div dir="ltr" style="text-align: justify;">In this best practices tutorial , I will discuss some little known practices which must be considered while handling exceptions in a robust application. Java provides many ways to handle exceptions like using try, catch and finally keyword. For more information about <a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/">java exception handling follow this link</a>. In Java we can also <a href="https://dineshonjava.com/user-defined-exception-in-java/">create new exceptions</a> and throw them using <a href="https://dineshonjava.com/difference-between-throw-and-throws-in/">throw </a>and <a href="https://dineshonjava.com/throws-keyword-in-java/">throws </a>keyword.</p>
<div id="ads-id" align="center"></div>
<p>In this java exception handling best practices tutorial I have mention near about top 10 to 20 java best practices to write exception handling code. Before going to read <a href="https://dineshonjava.com/exception-handling-and-checked-and/">this tutorial learn when to use checked vs unchecked exceptions in Java</a>.</p>
<h2><b>Type of Exceptions in Java</b></h2>
<ol style="text-align: left;">
<li>Checked Exceptions</li>
<li>Unchecked Exceptions.</li>
</ol>
<h2><b style="font-size: xx-large;">Checked Exceptions</b></h2>
<p>These are the type of exceptions for which the compiler checks to ensure that your code is prepared for handling such exceptions. These are the exceptions that you can expect to occur frequently and you must handle them in your code. The conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. But you can anticipate them and thus you must write code to deal with them. Programmatically, checked exceptions are the instances of the Exception class or one of its subclasses, excluding RuntimeException subtree.<br />
<b style="font-size: xx-large;"></b></p>
<h2><b style="font-size: xx-large;">Unchecked Exceptions</b></h2>
<p>The compiler does not check for such type of exceptions. Unchecked Exceptions comprise of run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing.</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/02/Exception.png" width="640" height="355" border="0" /></div>
<p> ;</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<h2><b><br />
</b> <b>Java Exception Handling Best Practices</b></h2>
<p><b>Use Checked Exception for Resolvable error and Unchecked Exception for run-time error.</b><br />
Use Checked Exception on these conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. Unchecked Exceptions comprise of run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing. You can not recover from an unchecked exception and you are not required to handle such type of exceptions either, but still you can do so if you want.</p>
<p><b>Declare the specific checked exceptions that your method can throw</b><br />
Always declare the specific checked exceptions that your method can throw. Suppose there are many such checked exceptions, you should probably wrap them in your own user defined exception and add information to in exception message. You can also use comma between multiple exceptions throws.</p>
<pre class="highlight">public void method() throws Exception { //Incorrect way 
} 
 
public void method() throws SpecificException1, SpecificException2 { //Correct way 
} 
</pre>
<p><b>Never throw any exception from finally block</b><br />
Finally block used for clean up operation and never throw any exception in this block. If clean up operation throw any exception then second exception will come out of method and the original first exception i.e. correct reason will be lost forever. In such condition you can also handle exception in the finally block.</p>
<pre class="highlight">try { 
 method(); //Throws exception One 
} finally { 
 cleanUp(); //If finally also threw any exception the exception One will be lost forever 
} 
</pre>
<p><b>Close or release resource in finally block</b><br />
Always release all resources after successfully completion or any occurring any exception between the process. So functionality like release resource, close connection of DB or Network. This is a well known best practice in Java. Closing resources in finally block guarantees that precious and scarce resource released properly in case of normal and aborted execution, guaranteed by finally block.</p>
<p><b>Use finally blocks instead of catch blocks if you are not going to handle exception</b><br />
If you don&#8217;t want to handle exception then always finally block with try instead of using try-catch. This is also a good practice.</p>
<pre class="highlight">try { 
 doSomething(); 
} finally { 
 cleanUp(); //do cleanup here 
} 
</pre>
<p>If above code you are accessing some method doSomething() but this method may throw some exception which you do not want to handle in own calling method, but still want some cleanup in case exception occur, then do this cleanup in finally block.</p>
<p><b>Always include all information about an exception in single log message</b><br />
<b>Don’t do this:</b></p>
<pre class="highlight">LOGGER.debug("Using cache sector A"); 
LOGGER.debug("Using retry sector B"); 
 
</pre>
<p><b>Do it like this:</b></p>
<pre class="highlight">LOGGER.debug("Using cache sector A, using retry sector B"); 
</pre>
<p><b>Throw only relevant exception from a method</b><br />
Always throw relevant exception from a method because it is important to keep application clean. Suppose a method which tries to make connection to DB if you throws NullPointerException then it will not give any relevant information to user. So either you could predefined relevant exception or you could make own custom exception.</p>
<p><b>Always provide meaning full message on Exception</b><br />
Always provide meaning full message of Exception to the logs because meaning full message helps to developer to find problem in the application. Always try to provide precise and factual information here. For example, compare these two Exception messages for IllegalArgumentException :</p>
<p>message 1: &#8220;Incorrect argument for method&#8221;<br />
message 2: &#8220;Illegal value for ${argument}: ${value}</p>
<p>first one just says that argument is illegal or incorrect, but second one include both name of argument and its illegal value which is important to point out cause of error.</p>
<p><b>Avoid empty catch blocks</b><br />
Never use empty catch block because it not just hides the Errors and Exception, but also may leave your object in unusable or corrupt state.</p>
<p><b>Never swallow the exception in catch block</b><br />
This point is also same as leaving empty catch block when handling the exception. Return null from catch block instead of handling the exception, it is cause of losing the error cause forever.</p>
<pre class="highlight">catch (NoSuchMethodException e) { 
 return null; 
} 
</pre>
<p><b>Use template methods for repeated try-catch</b><br />
For repeated catch block of same code in the many places in the application increase the duplicity of code, so always make a template method of this code and use this template method.</p>
<pre class="highlight">class DBUtil{ 
 public static void closeConnection(Connection conn){ 
 try{ 
 conn.close(); 
 } catch(Exception ex){ 
 //Log Exception - Cannot close connection 
 } 
 } 
} 
 
public void dataAccessCode() { 
 Connection conn = null; 
 try{ 
 conn = getConnection(); 
 .... 
 } finally{ 
 DBUtil.closeConnection(conn); 
 } 
} 
 
</pre>
<p><b>Never use exceptions for flow control in your program</b><br />
Exceptions are only erroneous condition in the application code but sometime developer use it as a flow control. Never do that.</p>
<pre class="highlight">try{ 
 conn.close(); 
} catch(Exception ex){ 
 //Writing application logic here 
} 
</pre>
<p><b>Always clean up after handling the exception</b><br />
Resources like DB connection, Network connections etc. should cleaned up after code execution either successfully completed or throwing any exceptions. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try – finally blocks.</p>
<p><b>Always catch only those exceptions that you can actually handle</b></p>
<pre class="highlight">catch (NoSuchMethodException e) { 
 throw e; //Avoid this as it doesn't help anything 
} 
</pre>
<p>If you can handle an exception then catch it otherwise re-throw it.</p>
<p><b>Converting Checked Exception into RuntimeException</b><br />
This is one of best practices of Exception Handling, many of frameworks like Spring adopt it for handling exception. According to it framework converts checked exception into RuntineException. For example in Spring JDBC framework has converted exception like SQLException wrapped into DataAccessException, an unchecked Exception. This Java best practice provides benefits, in terms of restricting specific exception into specific modules, like SQLException into DAO layer and throwing meaningful RuntimeException to client layer.</p>
<p><b>Including cause of Exception in stack-trace</b><br />
Java Exception class provides getCause() method to retrieve cause which can be used to provide more information about root cause of Exception. This Java best practice helps a lot while debugging or troubleshooting an issue.</p>
<p><b>Document Exception thrown by any method</b><br />
Should always make document for all exceptions which a piece of code may throw at runtime. This becomes increasingly important if you are writing API or public interface. With proper documentation of Exception thrown by any method you can potentially alert anyone who is using it.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;">
<h2><b>Related Posts</b></h2>
<ol style="text-align: left;">
<li><b><a href="https://dineshonjava.com/best-practices-for-java-naming-convention-in-programming/">Best Practices in Programming to Decide Name of Variables, Methods, Classes and Packages</a></b></li>
<li><b><a href="https://dineshonjava.com/exception-handling-and-checked-and/">Java Exception Handling</a></b></li>
<li><b><a href="https://dineshonjava.com/try-catch-block-and-handling-exceptions/">try &; catch block and Handling Exceptions</a></b></li>
<li><b><a href="https://dineshonjava.com/multiple-catch-block-handling/ "> Multiple catch block Handling<br />
</a></b></li>
<li><b><a href="https://dineshonjava.com/difference-between-throw-and-throws-in/"> difference between throw and throws in java<br />
</a></b></li>
<li><b><a href="https://dineshonjava.com/throws-keyword-in-java/">throws keyword in Java </a></b></li>
<li><b><a href="https://dineshonjava.com/exception-propagation-in-java/">Exception propagation in Java </a></b></li>
<li><b><a href="https://dineshonjava.com/handle-exceptions-in-overriding-methods/">Handle exceptions in overriding methods in Java </a></b></li>
<li><b><a href="https://dineshonjava.com/user-defined-exception-in-java/">User defined Exception in Java </a></b></li>
<li><b><a href="https://dineshonjava.com/different-exception-generate-in-array/">Different Exception Generate in Array in Java(7)</a></b></li>
<li><b><a href="https://dineshonjava.com/multiple-exceptions-in-java-7-new/">Multiple Exceptions In Java 7 New Concept </a></b></li>
</ol>
</div>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/best-practices-for-java-naming-convention-in-programming/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '62'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…