Laurens wrote:
> Are there any caveats to using ErrThrow in constructors?
> 
> I'm using PRC-Tools and want to have some structured error handling in
> my code. For instance, I'm allocating memory in the constructor and want
> to bail out as soon as possible in case this fails.
> 
> XMLReader::XMLReader (UInt16 bufferSize)
> {
>     m_buffer = MemPtrNew(bufferSize);
>     if (!m_buffer) {
>         ErrThrow(errNoMemory);
>     }
> }
> 
> Standard C++ exceptions apparently do not work with PRC Tools; the
> documentation states that "actually throwing an exception is probably
> currently broken anyway". I have to resort to the ErrTry, ErrThrow and
> ErrCatch macros.

I'd be surprised if ErrThrow / ErrTry / ErrCatch really work correctly
with all C++ constructs.  As I understand them, they are basically
just built on setjmp()/longjmp() type stuff.  So, all they are doing
is saving the stack pointer and other registers at a certain point, and
then if you return to that point, they just restore the stack and
register state by overwriting the registers.

A real exception mechanism would do more than just reset the stack;
it would unwind the stack and handle running destructors for all
objects whose scope disappears in the process.  For instance,
let's say you have a class Foo which does Important Cleanup in
its destructor, then let's say you do this:

        void dostuff ()
        {
            Foo foo(42);

            if (! thingy())
            {
                ErrThrow (errThingy);
            }

            foo.whatever();
        }
        
        int abc ()
        {
            ErrTry
            {
                dostuff ();
            }
            ErrCatch (err)
            {
            }
            ErrEndCatch
        }

What should happen here is that the instance of the Foo class should
be destroyed when the object goes out of scope at the end of dostuff().
But ErrThrow is just going to reset the stack and registers to how
they were was right at the point of ErrTry and then jump to the
ErrCatch block.  It does not know about the existence of the Foo
object and its destructor (since those are a language concept),
and so cannot call its destructor.

I haven't tested this scenario, so I can't say firsthand that it
will be a problem, but I don't know how it could possibly work
correctly.  So, I would be wary of mixing C++ with ErrThrow, etc.
If you did, then I would think you'd need to avoid putting any
objects on the stack (except possibly those whose destructor does
nothing -- which by the way breaks encapsulation).  Since that
would be a big handicap, I would probably look for some other
route than ErrThrow, etc.

  - Logan


-- 
For information on using the Palm Developer Forums, or to unsubscribe, please 
see http://www.palmos.com/dev/support/forums/

Reply via email to