lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Sep 17, 2014, at 9:18 PM, Andrew Starks <andrew.starks@trms.com> wrote:

On Thu, Sep 11, 2014 at 12:41 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
2014-09-11 2:43 GMT+02:00 Rena <hyperhacker@gmail.com>:

> The idiom I've heard and used is that returning (nil, errmsg) is for
> runtime errors, and error() is for programming errors. So e.g.:
> return nil, "Failed to open file: access denied"
> vs:
> error("Invalid argument to method frobulate (expected number)")

The question one should ask is: could one reasonably expect
the calling routine have a nice way of recovering from this error?
If so, return nil,error_obj; otherwise abort.

I've been thinking more about this topic.

So, the above quote from the illustrious Dirk seems to be "what smart people do." That is, there is a consensus around this view.

I don't think I understand it and I'm starting to think that "nil, error_msg" has no place in my code.

The problem with `nil, error` is that "reasonably expect" is both unknowable and possibly irrelevant:

1: I'm chugging along and the user tries to access a resource that doesn't exist.
2: That can happen and it's hard to even call that an 'error'. It's a normal thing that *will* happen, maybe even often.
3: So, I decide to return nil, 404 "resource gone mission’”

This whole thing is a horribly gray area (witness pretty much every single computer language). To my mind the nearest you can get is distinguishing between “expected” and “unexpected” conditions in a program (which is, of course, itself horribly vague). For “expected” conditions, I prefer to use some kind of return value, while for unexpected conditions I use some kind of exception/throw mechanism.

Example: FileOpen() fails because the file is not found. For me this is in the “return an error” bucket, since a program should always have code to cope with this, and that code should live close to where the file was opened.

Example: Out of memory error. This is an exception, since pretty much all a program can even hope to do is cleanup as gracefully as possible and bail out.

It really comes down to “where is the code that handles this condition?”. If it’s close to the code that caused it, then the whole apparatus of exceptions or pcalls() is just an ornate way of returning an error code from the callee to the caller. If it’s far away, then you WANT an exception model so that you can avoid the absurd “ripple through” model where error codes have to be returned up a winding call stack.

And yes, there are some nasty examples that sit right in the middle, which is why everyone argues for hours about stuff like this :)

—Tim