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.