how does exception mechanism work?
Tom Anderson
twic at urchin.earth.li
Mon Dec 12 19:18:28 EST 2005
On Mon, 12 Dec 2005, it was written:
> bobueland at yahoo.com writes:
>
>> Is this model correct or wrong? Where can I read about the mechanism
>> behind exceptions?
>
> Usually you push exception handlers and "finally" clauses onto the
> activation stack like you push return addresses for function calls. When
> something raises an exception, you scan the activation stack backwards,
> popping stuff from it as you scan and executing "finally" clauses as you
> find them, until you find a handler for the raised exception.
That varies an awful lot, though - AIUI, in java, the catch blocks are
specified sort of in the same place as the code; a method definition
consists of bytecode, a pile of metadata, and an exception table, which
says 'if an exception of type x happens at a bytecode in the range a to b,
jump to bytecode c'. When the exception-handling machinery is walking the
stack, rather than looking at some concrete stack of exception handlers,
it walks the stack of stack frames (or activation records or whatever you
call them), and for each one, follows the pointer to the relevant method
definition and inspects its exception table. Finally blocks are handled by
putting the finally's code right after the try's code in the normal flow
of execution, then concocting an exception handler for the try block which
points into the finally block, so however the try block finishes,
execution goes to the finally block.
The advantage of this approach over an explicit stack of handlers is that,
although unwinding the stack is perhaps a bit slower, due to having to
chase more pointers to get to the exception table, there's zero work to be
done to set up a try block, and since executing a try is a lot more
frequent than executing a throw-catch, that's a win.
Of course, that's how the conceptual virtual machine does it; real
implementations don't necessarily do that. That said, it is a traditional
superstition in java that a try block is essentially free, which would
suggest that this sort of implementation is common. Indeed, i see no
reason why it wouldn't be - i think the push-a-handler style seen in C/C++
implementations is only necessary because of the platform ABI, which
doesn't usually mandate a standard layout for per-function metadata.
tom
--
limited to concepts that are meta, generic, abstract and philosophical --
IEEE SUO WG
More information about the Python-list
mailing list