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:

Note the following about exceptions:

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.

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