Tuesday, October 09, 2012

Garbage collection makes it more practical to return good error messages

Elsewhere I have discussed how I buy into Andrei Alexandresciu and D's contention that throwing C++ style exceptions is the best way to signal errors, since a programmer cannot accidentally or deliberately forget to handle an error.  My preference is to throw generic string error messages, unless I am in a high reliability situation where errors will be parsed and try to be cured, since you can then at least provide a context,. or stack, of error messages.

But... languages with garbage collection do remove one objection to signalling errors by a return code.  One problem with return codes is that they are so cryptic.  Integers.  Ugh.   But if you can construct a meaningful string and return that, then the user at least has the option of printing a meaningful message.

     e.g.

             FUNCTION foo(int bar, char* file) RETURNS char* error_msg;

             if( char* error_msg = foo(42,"bazz") ) {
                     std::cerr << "call to foo got error message: " << error_msg << "\n";
             }

      versus

             foo(42,"bazz");    /// error code is ignored

At least with GC this pattern does not cause a memory leak.

---

I still prefer throwing C++ style exceptions, though.

1 comment:

  1. Annoyance for common unusual circumstances that can often be ignored would be constructing a meaningful message string, to have it ignored.

    Returning pointers to constant strings efficient enough. Especially if they could be treated as symbols, so address comparisons could be used.

    But for more detailed construction of string error messages, possibly a future: an object that is filled with stuff, that can be evaluated to return the universal data structure: a string, text.

    ReplyDelete