def
def

Reputation: 551

Implicit exception handling

I've got a basic idea of how exception handling is implemented by C++ compiler, credits to the excellent article by Vishal Kochhar. Basically, whenever the try/catch construct appears in a function, the compiler would generate a prologue/epilogue code, like this:

push -1
push offset new_handler
mov eax, fs:[0]
push eax ; old handler saved on the stack
mov fs[0], esp
...
mov ecx, [ebp-0Ch] ; recover old handler
mov fs[0], ecx

The question is, what is the reason the stuff like this is inserted by the compiler into the functions which seemingly have nothing to do with exception handling? I am certain, there is no try/catch blocks in their body, according to a source code.

Upvotes: 0

Views: 483

Answers (1)

Cauterite
Cauterite

Reputation: 1694

These functions "which seemingly have nothing to do with exception handling" are probably running finalisers/destructors on their local variables. An object's finaliser has to be run as soon as its scope ends, whether by normal return or by an uncaught exception, so functions must install an exception handler in the prologue to ensure finalisers are called in any case.

A simple example in D to trigger this behaviour:

struct Foo {
    ~this() {
        ;
    };
};

int main() {
    Foo x;
    return 0;
};

Perhaps a smart compiler would be able to omit the prologue/epilogue in a nothrow function e.g.:

struct Foo {
    ~this() nothrow {
        ;
    };
};

int main() nothrow {
    Foo x;
    return 0;
};

but not in this language it seems.

Upvotes: 1

Related Questions