When program execution ends with an error, an exception is thrown.

For example, a program might call a method with a null reference and throw a NullPointerException, or the program might try to refer to an element outside an array and result in an IndexOutOfBoundsException, and so on.

Handling exceptions

We use the try {} catch (Exception e) {} block structure to handle exceptions.

The keyword try starts a block containing the code which might throw an exception.

The block starting with the keyword catch defines what happens if an exception is thrown in the try block.

The keyword catch is followed by the type of the exception handled by that block, for example "all exceptions" catch (Exception e).

try {
    // code which possibly throws an exception
} catch (Exception e) {
    // code block executed if an exception is thrown
}

We use the keyword catch, because causing an exception is referred to as throwing an exception.

We have used the parseInt method of the Integer class before.The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer.

Exceptions and resources

There is separate exception handling for reading operating system resources such as files.

With so called try-with-resources exception handling, the resource to be opened is added to a non-compulsory part of the try block declaration in brackets.

ArrayList<String> lines =  new ArrayList<>();

// create a Scanner object for reading files
try (Scanner reader = new Scanner(new File("file.txt"))) {

    // read all lines from a file
    while (reader.hasNextLine()) {
        lines.add(reader.nextLine());
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

// do something with the lines

The try-with-resources approach is useful for handling resources, because the program closes the used resources automatically.

If the resources are not closed, the operating system sees them as being in use until the program is closed.

Shifting the responsibility

We can handle exceptions by wrapping the code into a try-catch block or throwing them out of the method.

A programmer can also leave the exception unhandled and shift the responsibility for handling it to whomever calls the method.

We can shift the responsibility of handling an exception forward by throwing the exception out of a method, and adding notice of this to the declaration of the method.