Sei sulla pagina 1di 3

7/15/13

10 Exception handling Best Practices in Java Programming

Javarevisited
Blog about Java Program Tutorial Example How to, Unix Linux commands, Interview Questions, FIX Protocol, Tibco RV tutorials, Equities trading system, MySQL

Java 6
MO NDA Y , MA R C H 25, 2013

Developers Java

Java Test Tool

Download Java JDK


Searc h

10 Exception handling Best Practices in Java Programming


Recent Posts
Exception handling is an important part of writing robust Java application. Its a non functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input and so on. Java provides several exception handling features, in built in language itself in form of t r y ,c a t c hand finally keyword. Java programming language also allows you to create new exceptions and throw them using throw and throws keyword. In reality, Exception handling is more than knowing syntax. Writing a robust code is an art more than science, and here we will discuss few Java best practices related to Exception handling. These Java best practices are followed even in standard JDK libraries, and several open source code to better deal with Errors and Exceptions. This also comes as handy guide of writing robust code for Java programmers.

When to make a method static in Java Top 5 JQuery books for Beginners and Web developers - Best of lot How SSL, HTTPS and Certificates works in Java web applications Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization 10 Java Exception and Error Interview Questions Answers 5 must read books to learn Object Oriented and Java Design patterns - Best of lot

Exception Handling Java Best Practices


Here is my collection of 10 Java best practices to write Exception handling code in Java. There have been both applause and criticism of checked Exception in Java, which is a language feature to force dealing with Exceptions. In this article, we will look to minimize use of checked Exception and learn when to use checked vs unchecked exceptions in Java as well. 1) Use Checked Exception for Recoverable error and Unchecked Exception for programming error. Choosing between checked and unchecked exception is always been confusing for Java programmers. Checked exceptions ensures that you provide exception handling code for error conditions, which is a way from language to enforcing you for writing robust code, but same time it also add lots of clutter into code and makes it unreadable. Also, it seems reasonable to catch exception and do something if you have alternatives or recovery strategies. See checked vs unchecked exceptions for more information on choosing between checked and RuntimeException in Java. 2) Close or release resource in finally block This is a well known best practice in Java and quite a standard, while dealing with networking and IO classes. Closing resources in finally block guarantees that precious and scarce resource released properly in case of normal and aborted execution, guaranteed by finally block. From Java 7, language has a more interesting automatic resource management or ARM blocks, which can do this for you. Nevertheless, always remember to close resources in finally block, which is important to release limited resources like F i l e D e s c r i p t o r s , used in case of both socket and files. 3) Including cause of Exception in stack-trace Many times Java library and open source code wraps one Exception into another, when one exception is thrown due to result of another exception. Its become extremely important to log or print cause of root exception. Java Exception class provides g e t C a u s e ( )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. Always remember to pass original Exception, into constructor of new Exception, if you are wrapping one exception into another.

4) Always provide meaning full message on Exception message of Exception is the most important place, where you can point out cause of problem because this is the first place every programmer looks upon. Always try to provide precise and factual information here. For example, compare these two Exception messages for I l l e g a l A r g u m e n t E x c e p t i o n: m e s s a g e1 :" I n c o r r e c ta r g u m e n tf o rm e t h o d " m e s s a g e2 :" I l l e g a lv a l u ef o r$ { a r g u m e n t } :$ { v a l u e }

Follow Us
Follow @javinpaul 3,239 follow ers

Javarevisited on
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. Always follow this Java b est practice, when writing code for handling exceptions and errors in Java.

Follow

+3,257

5) Avoid overusing Checked Exception Checked Exception has there advantage in terms of enforcement, but at same time it also litters the code and makes it unreadable by obscuring business logic. You can minimize this by not overusing checked Exception which result in much cleaner code. You can also use newer Java 7 features like one catch block for multiple exceptions and automatic resource management, to remove some duplication.

6) Converting Checked Exception into RuntimeException

javarevisited.blogspot.in/2013/03/0-exception-handling-best-practices-in-Java-Programming.html

1/3

7/15/13

10 Exception handling Best Practices in Java Programming


This is one of the technique used to limit use of checked Exception in many of frameworks like Spring ,where most of checked Exception, which stem from JDBC is wrapped into D a t a A c c e s s E x c e p t i o n , an unchecked Exception. This Java best practice provides benefits, in terms of restricting specific exception into specific modules, like S Q L E x c e p t i o n into DAO layer and throwing meaningful R u n t i m e E x c e p t i o nto client layer.

7) Remember Exceptions are costly in terms of performance One thing which is worth remembering is that Exceptions are costly, and can slow down your code. Suppose you have method which is reading from R e s u l t S e tand often throws S Q L E x c e p t i o nthan move to next element, will be much slower than normal code which doesn't throw that Exception. So minimizing catching unnecessary Exception and moving on, without fixing there root cause. Dont just throw and catch exceptions, if you can use boolean variable to indicate result of operation, which may result in cleaner and performance solution. Avoid unnecessary Exception handling by fixing root cause.

Javarevisited
8) Avoid empty catch blocks Nothing is more worse than empty c a t c hblock, because it not just hides the Errors and Exception, but also may leave your object in unusable or corrupt state. Empty catch block only make sense, if you absolutely sure that Exception is not going to affect object state on any ways, but still its better to log any error comes during program execution. This is not a Java best practice, but a most common practice, while writing Exception handling code in Java.
Like 4,660 people like Javarevisited.

9) Use Standard Exceptions Our ninth Java best practice advise on using standard and inbuilt Java Exceptions. Using standard Exception instead of creating own Exception every now and then is much better in terms of maintenance and consistency. Reusing standard exception makes code more readable, because most of Java developers are familiar with standard R u n t i m e E x c e p t i o n from JDK like, I l l e g a l S t a t e E x c e p t i o n ,I l l e g a l A r g u m e n t E x c e p t i o nor NullPointerException, and they will immediately be able to know purpose of Exception, instead of looking out another place on code or docs to find out purpose of user defined Exceptions. 10) Document Exception thrown by any method Java provides throw and throws keyword to throw exception and in javadoc you have @ t h r o wto document possible Exception thrown by any method. 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. That's all on Java best practices to follow while handing Exceptions in Java. Do let us know what practices you follow while writing Exception handling code in Java.

F acebook social plugin

Recommendd Books Java Programming and Design Pattern Spring Framework Subscribe by email: Subscribe By Javin Paul Subscribe To This Blog Free Posts Comments

Related Java Best Practices tutorials from Javarevisited blog How to write Production Quality Code in Java Top 10 JDBC Best Practices for Java Programmers Code review Checklist and best practices 10 tips to follow while writing Code Comments in Java Java best Practices for overloading and overriding methods

Followers Join this site


w ith Google Friend Connect

Members (1250) More

Please share with your friends if like this article


Already a member? Sign in

Internet marketing strategies


You might like:

Business Ideas

Moving Service

Performance Review

Difference between Wait and Sleep , Yield in Java Checked vs Unchecked Exception in Java Example How to use jdk7 multi-cache block with example Top 10 Collection Interview Questions Answers in Java
Recommended by

Learn Java Programming Java Troubleshooting Java J2EE Developers


Blog Archive 2013 (97) July (4) June (9)
+21 Recommend this on Google

Posted by Javin Paul at 6:30 AM

May (14) April (18) March (16) How to Convert and Print Byte array to Hex String ... 10 Exception handling Best Practices in Java Progr... How to Reverse Array in Java - Int and String Arra...

Labels: best practices, core java, error and exception, programming

Online Learning Problems

Long distance moving Programm

Programming Software

Functional Requirement Business Ideas

Internet marketing strategies

6 comments:
Anonymous said...

javarevisited.blogspot.in/2013/03/0-exception-handling-best-practices-in-Java-Programming.html

2/3

7/15/13
Good :) March 25, 2013 at 10:12 PM Anonymous said... Nice.... March 27, 2013 at 1:11 PM Anonymous said...

10 Exception handling Best Practices in Java Programming


How to check if two String are Anagram in Java - P... How to generate MD5 Hash in Java - String Byte Arr... 10 Famous Laws of Computer Programming and Softwar... Can we Overload and Override Static methods in Jav... Top 15 Data Structures and Algorithm Interview Que... Difference between Struts 1 and Struts 2 framework... Bitwise and BitShift Operators in Java - AND, OR, ... Difference between Singleton Pattern vs Static Cla... How to Increase Console Buffer Size in Eclipse IDE... ReentrantLock Example in Java, Difference between ... 5 books to learn Spring framework and Spring MVC f... How to create Immutable Class and Object in Java -... How to write Unit Test in Java using JUnit4 in Ecl... February (18) January (18) 2012 (218) 2011 (145) 2010 (33)

Nine out of ten are items in "Effective Java, Second Edition." If that's not just coincidence, if you were inspired by that book, it seems fair to give the authors credit. March 28, 2013 at 6:57 AM Javin @ Java Classloder Working said... @Anonymous, If that's the case, then it just a coincidence mate. Though I did read the book, and I am big fan of him, this post was mainly a collection of best practices, what I follow. To be fair, every one with few years of experience in Java knows about it, it's more Java programmer with couple of years experience. Having said, that I highly recommend Effective Java to any Java developer, you can also read it about in my post of 5 good books for Java Programmer March 28, 2013 at 6:54 PM Anonymous said... this one is worth a couple reads...good stuff, man April 1, 2013 at 11:00 PM Palak said... Hi Javin, Can you please share tips to write robust code, I mean code which handles exceptional scenario gracefully e.g. reading a malformed message if you are expecting a fixed length binary message, or an XML which doesn't has required XPATH . Most importantly how to find those exceptional scenario and how to decide action needs to be taken on that time? April 29, 2013 at 11:22 PM

Post a Comment
References E n t e ry o u rc o m m e n t . . . Java API documentation JDK 6 Spring framework doc Struts ANT Maven Comment as: Google Account Publish Preview JDK 7 API MySQL Linux Eclipse Copyright by Javin Paul 2012. Powered by Blogger.

Newer Post Subscribe to: Post Comments (Atom)

Home

Older Post

About Me

Privacy Policy

javarevisited.blogspot.in/2013/03/0-exception-handling-best-practices-in-Java-Programming.html

3/3

Potrebbero piacerti anche