1. What are exceptions?

1.1. Definition

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

1.2. Throwing an exception

It happens when an error occurs the method creates an exception object and hands it off to the runtime system.

Figure 6.1. Call Stack

Call Stack

1.3. The exception object

The exception object contains information about the exception, including its type and the state of the program when the error occurred.

1.4. Catching an exception

It happens when the exception object bubbles up through the call stack until an appropriate exception handler is found. The handler catches the exception.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception.

Figure 6.2. Catching an Exception

Catching an Exception

1.5. Advantages

1.5.1. Advantage 1: Separating Error Handling Code from "Regular" Code

Table 6.1. Advantage 1

errorCodeType readFile {
    initialize errorCode = 0;
    open the file;
    if (theFileIsOpen) {
        determine the length of the file;
        if (gotTheFileLength) {
            allocate that much memory;
            if (gotEnoughMemory) {
                read the file into memory;
                if (readFailed) {
                    errorCode = -1;
                }
            } else {
                errorCode = -2;
            }
        } else {
            errorCode = -3;
        }
        close the file;
...  
}
readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
        doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }


}

Audio in Portuguese

1.5.2. Advantage 2: Propagating Errors Up the Call Stack

Table 6.2. Advantage 2

method1 {
    errorCodeType error;
    error = call method2;
    if (error)
        doErrorProcessing;
    else
        proceed;
}
errorCodeType method2 {
    errorCodeType error;
    error = call method3;
    if (error)
        return error;
    else
        proceed;
}
errorCodeType method3 {
    errorCodeType error;
    error = call readFile;
    if (error)
        return error;
    else
        proceed;
}
method1 {
    try {
        call method2;
    } catch (exception) {
        doErrorProcessing;
    }
}
method2 throws exception {
    call method3;
}
method3 throws exception {
    call readFile;
}












1.5.3. Advantage 3: Grouping Error Types and Error Differentiation

Figure 6.3. Advantage 3

Advantage 3

catch (ArrayException e) {
    . . .
}
catch (Exception e) {
    . . .
}

Audio in Portuguese