Introducing Exceptions in Java

In our introduction to Java error handling, we said that Java has a mechanism called exceptions. Exceptions are a means of dealing with error conditions where in other languages, workaround techniques need to be used such as reserving a special return value to indicate "error".

The easiest way to understand exceptions is dive straight in and look at an example. This is what one if the constructors to the FileInputStream class looks like:

public FileInputStream(File file) throws FileNotFoundException;

What this signature is telling us is that the constructor to FileInputStream, instead of giving us the constructed object, can instead "throw" an error condition back to us represented by an object of type FileNotFoundException. Now, to call this constructor, we have to add a piece of code to deal with the error condition:

try {
 FileInputStream fin = new FileInputStream(file);
 // No error occurred: read data from fin
} catch (FileNotFoundException fnf) {
 // Oh dear, error occurred opening file
 displayErrorMessage(fnf.getMessage());
}
// Do next bit

If the constructor to FileInputStream completes normally, we'll be returned a FileInputStream object as expected. Otherwise, if a FileNotFoundException is thrown, Java will jump to the section of code that catches the exception. Note that these are the only two possibilities:

  • The constructor to FileInputStream must return a constructed FileInputStream object, else throw an exception;
  • The code inside the catch block will be executed if and only if an exception occurs. Under normal execution, once the code inside the try block completes, Java skips past any related catch block (to where the comment "do next bit" is in the example above);
  • Similarly, the remaining lines inside the try block will be executed if and only if the constructor completes without error.

Note the following about exceptions:

  • A single catch block will be called when the given exception happens on any line inside the try block; we don't have to repeatedly check for an error condition after every line of code, as in the typical C idiom;
  • An exception is an object, so it has properties, such as an error message that we can query;
  • Because an exception is an object, this allows for a hierarchy of exception types. As we'll see later, FileNotFoundException is actually a subtype of an exception class called IOException.

The try/catch block in more detail

On the next page, we expand on the points above, and look at the try/catch block in more detail.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.

AltStyle によって変換されたページ (->オリジナル) /