Friday, November 09, 2018

What are exceptions?

What are exceptions?

Essentially, exceptions are a form of structured, non-local goto with stack unwinding. "Structured" here means "higher level than the machine" (a matter of taste/opinion), and "non-local" means "beyond a single function/method".

What this means is that you can replace code like (in "C"):

int bottom()
{
    int things_go_wrong = -1; // For illustration

    if (things_go_wrong) goto error;
    return 0;

error:
    return -1;
}

int
middle()
{
    if (-1 == bottom()) goto error;
    return 0;

error:
    return -1;
}

void
top()
{
    if (-1 == middle()) {
        handle_failure();
    }
}

With code like (in Java):

public class A {
    void botton() {
        boolean thingsGoWrong = true; // For illustration

        if (thingsGoWrong) throw new ThingsWentWrong("So wrong!");
    }

    void middle() {
        bottom();
    }

    void top() {
        try {
            middle();
        } catch (ThingsWentWrong e) {
            handleFailure();
        }
    }
}

(An example in Scheme.)

"Unwinding" here means the compiler or runtime treats intermediate calls (the stack) the same as if returning normally (for example, the stack pointer is moved back; and in a language like C++, destructors are executed), and program execution resumes in the catch block.

It is "structured" in the sense that it is not the same as a direct goto to the resume point. This is not possible in standard "C" or C++ (or in Java), which only suppport local labels within functions. The equivalent in "C" and C++ is to use setjmp and longjmp for a non-local goto, and forget all about deallocating memory or calling destructors. (As odd as this sounds, it is needed for call-with-continuation, an important feature in LISP-like languages).

Takeaway

All human endeavors build on the work of those who came previous. Exceptions are no exception. They are the result of 1960s and 1970s programmers wanting an easier way to deal with exceptional conditions. This is not completely identical with "errors", which may sometimes be better represented with a simple boolean true/false return. Like any sharp instrument, do not abuse it.

Post a Comment