Exceptions

Is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Specifying the Exceptions Thrown by a Method

public void writeList() throws IOException, IndexOutOfBoundsException {
   ...
}

To specify that method can throw an exception, add a throws clause to the method declaration for the method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method.

Advantages of Exceptions

  • Advantage 1: Separating Error-Handling Code from "Regular" Code. Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.
  • Advantage 2: Propagating Errors Up the Call Stack. A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods.
  • Advantage 3: Grouping and Differentiating Error Types. Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.

How to Throw Exceptions

public Object pop() {
    Object obj;

    if (size == 0) {
        throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}

Exception is always thrown with the throw statement.

The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class.

Exceptions — Structure map

Clickable & Draggable!

Exceptions — Related pages: