Hacker News new | ask | show | jobs
by WalterBright 1777 days ago
The FPU does not include the source in the NaN, but that doesn't mean your own objects can't.

What I do is have the error reported at the source, and then return the poisoned object. A better way would possibly be put the error message in the poisoned object, and report the error somewhere up the call stack.

2 comments

I do that a lot with the firmware I write in C.

  typedef struct
  {
    err_t error;
    int error_line;
    char *error_msg;
    ...
    ...
  } thing_t;

  // set out of range error
  thing->error = THING_ERROR_OOR;
  thing->error_line = __LINE__;
  thing->error_msg = "outofrange"
You can grep on 'outofrange' and find where the error was set.

I originally started doing that to mark 'bad' analog readings in process control equipment. I wrote my filters and control loops to be able to 'eat' occasional bad readings without barfing. Worked very well.

I often using something like this in C++

    if( nullptr != pfnErrorSink )
        pfnErrorSink( "outofrange", __FILE__, __LINE__ );
    return E_BOUNDS; // Or sometimes throw E_BOUNDS;
Where pfnErrorSink is either global, thread_local or a field keeping C function pointer provided by whoever consumes the code.
What are the return values from a poisoned object’s methods? Does a poisoned vector have a poisoned integer as its size?
> What are the return values from a poisoned object’s methods?

That's up to you. You can do it as:

1. return a poisoned value

2. return a safe value, like `0` for its size

3. treat it as a programming bug, and assert fail

4. I know `null` is hated, but it is the ultimate poisoned value. Try to call a method on it, and you are rewarded with a seg fault, which can be considered an assert fail.

5. design your poisoned object to be a real object, with working methods and all. It can be the same as the object's default initialized state.

In other words, it's necessary to think about what the poisoned state means for your use case. I use all those methods as appropriate.