Home  Exceptions  try/catch  finally  Throwing  Exception hierarchy  Unchecked exceptions  Exception recasting  Uncaught exceptions

Exceptions and error handling in Java

If you've programmed in a language such as C, you may be used to code that looks something like this:

FILE *fpt = fopen(file, "rb");
if (!fpt) {
  // some error occurred -- find out what
} else {
  // read from file

or, particularly if you've used Microsoft APIs, this:

int status, result;

result = spurious_function(&status);
if (!isErrorStatus(status)) {
  result = processResult(result, &status);
if (!isErrorStatus(status)) {
  // etc...
// use result

The problems of this approach are almost self-illustrating. In the first example, it is up to the programmer to know and remember to check the appropriate return value, or worse, to have to check multiple possible return values against a known list. Sometimes finding out what the actual error was, and the appropriate error message to give to the user, can be extremely fiddly. In C, any case where it's more or less inevitable that an error will occur at some point– such as dealing with files– can be particularly irritating and can involve practically every line of code being placed inside an if() clause or equivalent. The second idiom, where we have a separate status variable, at least allows multiple calls to be chained together, but we still have to faffily check the variable on each call.

Where we're carrying out a sequence of actions, such as opening and then reading multiple items from a file, it's also up to the programmer to ensure that any "tidying up" code happens in either case. For example, if we're reading from a file, we need to make sure that the file is closed if at least the initial open succeeds, whether or not one of the subsequent read operations fails.

As we'll see on the next page, Java (like some other modern languages) gets round these problems with an exception mechanism.

comments powered by Disqus

Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey. Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.
Search this site:
Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java

 What do you think of this article? Did it help you? Found a mistake? Feedback and suggestions here