Developer

Roll your own Java exceptions and avoid playing 'catch'

Creating your own exceptions can provide a quick way to deal with odd conditions in your applications. One member explains how to put this trick to good use.


There's little doubt that Java's exception system is a good thing, but many programmers don't take full advantage of it. That's the origin of this week's Java programming tip, courtesy of John Jennings, who sent it in to us from Ireland.

Handling exceptional conditions
"Java provides its own exceptions, and the built-in system is adequate for most situations. But you can create and throw your own exceptions too, and you don't have to worry about providing code to 'catch' them. They'll travel up the call chain to the first available exception handler.

"One useful application is where you really want to capture an error but you don't expect it to happen normally. (That is the origin of the word 'exception,' after all.) If one of those oddball situations does occur, you can quickly code a single line that will print an identifying message and a stack dump on the console, which will help you resolve the situation.

"For example, if I have a switch statement where I always expect the variable c to be equal to 0,1, or 2, I can use something similar to the following to alert me if c ever happens to deviate from my expectations:
 
switch (c) {
   case 0: return 'X'; break;
   case 1: return 'Y'; break;
   case 2: return 'Z'; break;
   default: throw new RuntimeException("Invalid value in switch statement! ("+c+").");
}

"The resulting code won't win any beauty awards, but if the error never arises, you don't ever see the message. But if it ever does, you'll know! Also, note that there's no code needed to catch this error in my routine."

Got a hot tip?
Send us your Java programming tips. If we use one in this column, you'll score yourself one of our coveted super-size TechRepublic coffee mugs. Rather appropriate for a Java tip, don't you think?

 

Editor's Picks

Free Newsletters, In your Inbox