Who handles errors

You have learned somewhere that a function should return error codes.  When you become a team leader, you take it serious and let everyone write functions to return error codes.

Then the program tends to be like this:

bad:

    int func1() {
        .....
        if (error) return -1;
        .....
    }

    int func2() {
        .....
        status = func1();
        if (status != 0) return status;
        .....
    }

    int func3() {
        .....
        status = func2();
        status = func2();
        .....
    }

    int func4() {
        .....
        status = func3();
        if (status != 0) return status;
        .....
    }

You set up a rule and let everybody follow. Your program will be robust.

Wrong. You only have false sense of assurance. Error code works only if all the caller check the error code and pass it along accordingly. That is very unlikely; for example, in the example above, the error code returned from func2() is ignored in func3().

This is more dangerous than doing nothing, and creates lots of unnecessary coding work.

More realistic way is just to stop at error, and not returning error code at all.

good:

    void func1() {
        .....
        assert(!error);
        .....
    }

    void func2() {
        .....
        func1();
        .....
    }

    void func3() {
        .....
        func2();
        .....
    }

    void func4() {
        .....
        func3();
        .....
    }

This looks brutal for production level program. But in reality it is much better than the first example because it catches the error.

But what if you want to continue even if the error occurs? I recommend error logging. There is no need to propagate the error during the call tree. And the error is guaranteed to be checked eventually.

good:

    void func1() {
        .....
        if (error) logWrite(error);
        .....
    }

    void func2() {
        .....
        func1();
        .....
    }

    void func3() {
        .....
        func2();
        .....
    }

    void func4() {
        .....
        func3();
    if (logShowsError()) {
            // Take some action.
        .....
        logClear();
    }
        .....
    }

As a rule of thumb, error return is OK only for a simple functions.

By the way I didn’t mention about exception (the try and catch construct). I use exception for my private programming. However, I found it too difficult for the group of ordinary people which I have been working with. Only a few of them would understand what they are told to do.

Advertisements