Robert Fisher

Just thinking out loud

On exceptions

If you register and log in you can add comments to my pages. If viewing the main blog page, click the # underneath an entry to comment on it.

Recently, I've had to write some C++ code & couldn't use exceptions. This reëmphasized to me what a boon they are. Consider this contrived example:

void foo()
{
    result_t rc(RESULT_OK);

    rc = foo_1();
    if(RESULT_OK != rc) {
        report_error(rc);
        return;
    }

    rc = foo_2();
    if(RESULT_OK != rc)
        report_error(rc);
}

result_t foo_1()
{
    result_t rc(RESULT_OK);

    rc = foo_1_1();
    if(RESULT_OK != rc)
        return rc;

    rc = foo_1_2();
    if(RESULT_OK != rc)
        return rc;

    return RESULT_OK;
}

result_t foo_1_1()
{
    errno = 0;
    bar();
    if(0 != errno)
        return rc_from_errno(errno);

    return RESULT_OK;
}

That code spends so much time checking & rechecking for error conditions. Now consider the same thing with exceptions.

void foo()
{
    try {
        foo_a();
        foo_b();
    } catch(my_exception& e) {
        e.report();
    }
}

void foo_a()
{
    foo_a1();
    foo_a2();
}

void foo_a1()
{
    errno = 0;
    bar();
    if(0 != errno)
        throw my_errno_exception(errno);
}

An error is only checked where it happens & is only reported/handled where it can be. The intervening code remains simple.

Now imagine a real program...

  • More steps...foo_1()–foo_20()
  • More depth...foo_1_1_1_1_1()–foo_20_20_20_20_20()
  • Not all errors are detected at the lowest depth.
  • Not all errors are reported/handled at the highest depth.

Exceptions can be a big win in cleaner, simpler, quicker to write, easier to maintain code—even if the implementation does have a performance hit.

Although this does gloss over the dtors or finally blocks that are needed to ensure proper clean-up when an exception happens. (But you need that without exceptions as well.)