Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Concentrate on the Java Exceptions that Matter to Your Application

Using custom exceptions that separate application from system exceptions enables you to concentrate on handling only the exceptions that are meaningful to your application.


advertisement
xceptions, indicators of abnormal conditions that disrupt the normal flow of a program, are a prominent fixture of the Java language. You have to handle exceptions to write a useful Java program.

Java classifies exceptions as either checked or unchecked and, as with everything else, represents them as objects. Checked exceptions extend java.lang.Exception, and they must be handled by a try/catch block or a throws clause for compilation to proceed. Unchecked exceptions extend java.lang.RuntimeException, and they are not checked by the compiler.

Although extremely helpful, Java's checked exceptions mechanism has an unwanted side effect: the "try/catch/do nothing" code block:



try { // Some code that generates checked exceptions } catch(Exception e) { // do nothing }

Many articles have warned against the problems this coding practice causes and encouraged developers to avoid it. Yet it is still prevalent in Java code. Aside from bad programming, a main reason for this practice is that developers don't know what to do with generated exceptions: some Java APIs generate more than one exception and how to handle them or which code to write in the catch code block is not always clear.

The easiest solution is to delegate responsibility for exception handling to other parts of an application using the methods you wrote: simply throw exceptions that you don't want to handle. In n-tiered applications, however, this means an exception could be thrown again and again until it ends up in a "try/catch/do nothing" block. If you write a method that throws a java.sql.SQLException because you don't know what to do with the exception, then most certainly other developers using your method won't know how to handle it either.

This article presents an easy way to relieve Java developers from worrying about what to do with exceptions that don't relate directly to their applications, allowing them to concentrate on handling only the exceptions that affect the flow of their applications.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap