C++ and system exceptions

Posted by Abyx on Programmers See other posts from Programmers or by Abyx
Published on 2011-12-07T14:47:10Z Indexed on 2012/06/08 4:46 UTC
Read the original article Hit count: 256

Filed under:
|
|

Why standard C++ doesn't respect system (foreign or hardware) exceptions?

E.g. when null pointer dereference occurs, stack isn't unwound, destructors aren't called, and RAII doesn't work.

The common advice is "to use system API". But on certain systems, specifically Win32, this doesn't work. To enable stack unwinding for this C++ code

// class Foo;
// void bar(const Foo&);
bar(Foo(1, 2));

one should generate something like this C code

Foo tempFoo;
Foo_ctor(&tempFoo);
__try {
    bar(&tempFoo);
}
__finally {
    Foo_dtor(&tempFoo);
}
Foo_dtor(&tempFoo);

and it's impossible to implement this as C++ library.


Upd: Standard doesn't forbid handling system exceptions. But it seems that popular compilers like g++ doesn't respect system exceptions on any platforms just because standard doesn't require this.

The only thing that I want - is to use RAII to make code readable and program reliable. I don't want to put hand-crafted try\finally around every call to unknown code. For example in this reusable code, AbstractA::foo is such unknown code:

void func(AbstractA* a, AbstractB* b) {
    TempFile file;
    a->foo(b, file);
}

Maybe one will pass to func such implementation of AbstractA, which every Friday will not check if b is NULL, so access violation will happen, application will terminate and temporary file will not be deleted. How many months uses will suffer because of this issue, until either author of func or author of AbstractA will do something with it?


Related: Is `catch(...) { throw; }` a bad practice?

© Programmers or respective owner

Related posts about c++

Related posts about exception-handling