Main Content

Fail Safe Error Handling in Java via Exceptions

Archive - Originally posted on "The Horse's Mouth" - 2010-07-09 07:07:34 - Graham Ellis

"What could possibly go wrong?" ... The usual answer from a cynic is "anything, and usually at the most inconvenient time, and in the most unexpected way!". So checking for routine errors in your program code is a good start, but it doesn't go far enough; you need to be able to handle errors which are not routine, and are not anticipated - and that's where the "exception" system comes in.

Exceptions work like this ... you put the section of code that you want to "mop up" any problems from in a try block, and you then provide one or more catch blocks as safety nets - they'll be run only if a certain class of exception is thrown. Multiple safety nets (i.e catch blocks) allow you to trap very specific and narrowly defined issues first, then have further more general nets available if the first ones don't work.

On most exception systems (including Java, who's terminology I've been using so far) you also have the ability to define a clean up block that is always run - a finally block - irrespective of whether or not an excpetion you've caught has cause the code to exit prematurely rather than carry on below (fall through).

There's an example showing the code that relates to each of these concepts [here] from yesterday's Java Bootcamp. It goes little further in that it also illustrates how a method can pass back an exception to the code that called it (rather like a chid asking its mother for help!), and it even defines its own special class of exception, showing how the mechanism can be used to pick up run time problems in your code, as well as in the standard library calls that you make. The source of the extra class that defines your own exception is [here]