Home > Articles > Programming > Java

Avoiding Java Exception Abuse

Marcus Zarra
  • PrintPrint
  • Share ThisShare This
  • DiscussDiscuss
Close WindowMarcus Zarra

Marcus Zarra

Learn more…

Basic Animations with Core Animation
Dec 28, 2009
Marcus Zarra and Matt Long on Core Animation
Jun 5, 2009
Introduction to Migration in Apple's Core Data
Mar 7, 2008
A Look at Apple's Core Animation
Feb 1, 2008
The State of Java Development on OS X
Jan 4, 2008
Packaging Your Application for OS X
Nov 21, 2007
Tiger vs. Leopard: Which Should You Develop For?
Oct 26, 2007
Building on Apple Sync Services
Sep 8, 2006
Getting in Sync with OS X
Sep 1, 2006
Syncing Your Data the Cocoa Way
Aug 11, 2006
Controlling Both Ends of the Communications Channel: From Cocoa to Servlets
Jun 2, 2006
Cocoa: Working with XML
May 19, 2006
Java EJB 3.0: A Hibernate Clone?
Apr 28, 2006
Document Level Parameters Using Core Data: A Guide for Cocoa Developers
Apr 7, 2006
Tips for J2EE Development
Feb 24, 2006
The Cross-Platform Java GUI: Designing Code for More Than One Operating System
Feb 10, 2006
Avoiding Java Exception Abuse
Dec 22, 2005
Java Perspective: Advanced Core Data
Dec 16, 2005
Java Perspective: Cocoa-Java Bridge
Dec 1, 2005
Java Perspective: Core Data and the Mac OS X Developer
Nov 23, 2005
Java Perspective: Key-Value Protocols, Behind the Magic of Mac OS X Development
Nov 11, 2005
Java Perspective: Cocoa Subclasses and Delegates
Nov 4, 2005
The Java Perspective: Cocoa's Interface Builder
Oct 21, 2005
Maven: Handling Multiprojects
Sep 23, 2005
Java, Maven, and Your Web Development Project
Aug 26, 2005
Ant User, Let Me Introduce Maven
Jul 29, 2005
Using JAAS Authentication with JBoss
Jun 17, 2005
Building a Custom JBoss Login Module
Jun 10, 2005
Testing Java Enterprise Applications with Cactus
May 20, 2005
Ant: Building a Better Build File
May 6, 2005
XDoclet: Entity Bean Relationships
Apr 8, 2005
The Java Developers' Introduction to XDoclet
Jan 7, 2005
An Introduction to Cactus
Dec 30, 2004
Using Multiple Databases with JBoss
Nov 24, 2004
JBoss Application Configuration Breakdown
Nov 5, 2004
Sortable Swing JTable
Oct 1, 2004
Building a Professional Swing JTable
Sep 10, 2004
Creating a Custom Java Swing Tablemodel
Aug 27, 2004
Adding Workflow Control to Your Java Applications
Mar 26, 2004
The Mac Developer Network
By on November 21, 2007 No Comments
Steve Scott of Late Night Cocoa has started a new podcast targeted specifically at Macintosh Developers.  One of the first episodes on this podcast is a roundtable of developers with several very well known developers starting with Daniel Jalkut, Uli Kusterer and Fraser Spiers along with myself.
Once more unto the [Beta Cycle], dear friends, once more
By on November 16, 2007 No Comments
Today marks the first semi-public release of iWeb Buddy, a new application that I have been developing for the past few months.  Unlike seSales or applications developed as a consultant, this development cycle has been a blur of activity.
Apple -- You Did Me A Disservice
By on October 26, 20073 Comments
Today is the day that most Mac users have been looking forward to for over a year.  Ever since Steve Jobs got up on stage last August and showed us Leopard for the first time.  Ever since that first peak almost all Mac users and I dare say ALL Mac developers have been looking forward to this release.  Unfortunately, today is also a day that Mac developers are going to be scrambling like rats on a burning ship.  This is because Apple decide to thumb their nose at us.
Further development of Bullfrog 2 for OS X
By on October 11, 2007 No Comments
Things are starting to speed up on the development of Bullfrog 2 previously mentioned here.  In our continuing disclosure about the development process, Jon Trainer has written a very informative article on how the actors are configured.
Starting over is hard to do
By on September 18, 2007 No Comments
I mentioned before that I am working with Jon Trainer of Outer Level to write Bullfrog 2 for OS X.  This development effort will be targeted at the as of yet unreleased OS X 10.5 Leopard.  We also promised to blog about the development as it moved forward.  Unfortunately not everything has been roses.
There are always exceptions to the rule, right? In Java, those exceptions allow a clean break from normal program flow in the event of an exceptional situation. They're not used for program flow interruption, but for program flow branching, which can sometimes lead to difficult-to-maintain code. Marcus Zarra walks you through several best practices for using exceptions in Java.

The capability to throw exceptions in Java gives a much-needed flexibility to the language. By being able to exit from the normal program flow, code can remain clear and easy to maintain. As is usual, with this added flexibility comes the temptation to abuse it. It is quite common to use exceptions as a way to exit out of a method during normal program flow. Although this style of programming is tempting, it is an abuse of exceptions that causes the code to be difficult to maintain and debug.

Return Early, Return Often

One of the most common abuses of exceptions is an attempt to avoid returning early. Edsger W. Dijkstra is often credited with claiming that methods should always have a single exit point. Although I disagree that Dijkstra claimed this, there has been a school of thought following the single exit point strategy. Trying to force a single exit point in a Java method often leads to clunky and unmaintainable code.

Programmers attempting to avoid layers and layers of nested code end up using exceptions to exit early in an attempt to avoid multiple exit points. Following this strategy, the programmer ends up with code that has to use a try/catch block instead of a simple conditional. Imagine a method that throws an exception instead of returning a false. The code that calls that method might look something like this:

try {
 chargeCustomerCard(variable1, variable2);
  updateDatabaseWithSuccessfulCharge(variable1, variable2);
} catch (Exception e) {
  updateDatabaseWithFailedCharge(variable1, variable2);
}

In this example, the catch block is used instead of a false result from the chargeCustomerCard() method. Of course, this begs the question, what happens if the chargeCustomerCard() throws a "real" exception? How is that handled? That might lead to further confusion:

try {
 chargeCustomerCard(variable1, variable2);
  updateDatabaseWithSuccessfulCharge(variable1, variable2);
} catch (CreditCardException e) {
  logCreditCardException(variable1, variable2);
} catch (Exception e) {
  updateDatabaseWithFailedCharge(variable1, variable2);
}

As you can see, this quickly gets out of hand. Normal program flow is getting mixed up with exceptional situations. To avoid this, throw exceptions only for exceptional situations and use return codes or boolean values to control program flow:

try {
 if (chargeCustomerCard(variable1, variable2)) {
   updateDatabaseWithSuccessfulCharge(variable1, variable2);
  } else {
   updateDatabaseWithFailedCharge(variable1, variable2);
  }
} catch (CreditCardException e) {
  logCreditCardException(variable1, variable2);
}

This process not only produces code that is easier to read but it also allows unexpected exceptions to bubble up through the code to be either dumped out by the JVM or caught at a higher level.

Avoid putting yourself into this situation. If it makes sense to return from a method early, do so. Don’t throw an exception just to avoid multiple return points. In addition, check for known false results. If, in the above example, variable1 must be of a certain length, check the length—if it is wrong, return immediately. Returning early because of known bad situations will make the code easier to read and keep the proper path on the left margin of the method. This will be easier to maintain.

  • Share ThisShare This
  • Your Account

Discussions

Make a New Comment

You must log in in order to post a comment.

Related Resources

Jennifer  BortelWin FREE iPhone Developer Books and Videos- Introducing @InformIT Giveaways
By Jennifer Bortel on February 5, 2010 No Comments

Apples’s recent iPad announcement made our hearts flutter so we couldn’t resist making an announcement of our own!

Today marks the first ever @InformIT Giveaway!

We’ll regularly post a video like this one profiling spectacular prizes we’re giving away—from books and videos to T-shirts and other exciting stuff. Check out the video below to see the giveaways for today, and then scroll down for more prize details and instructions on how to win them!

Dustin Sullivan"Every OSX developer should have this book on their desk."
By Dustin Sullivan on February 1, 2010 No Comments

That was the sentence Mike Riley ended his recent Dr Dobb's CodeTalk review of Cocoa Programming Developer's Handbook with.

David ChisnallCocoa Tip of the Day, 1/29/10
By David Chisnall on January 29, 2010 No Comments

Don't ignore old versions of OS X.

See All Related Blogs

Informit Network