[ACCEPTED]-How does C++ exception handling translate to machine code-try-catch

Accepted answer
Score: 25

Poor implementations of exception handlers 43 push some kind of exception handler block 42 for each try clause on the runtime stack 41 as the try clause is entered, and pop it 40 off as the try clause is exited. A location 39 holding the address of the most recently 38 pushed exception handler block is also maintained. Typically 37 these exception handlers are chained together 36 so they can be found by following links 35 from the most recent to older versions. When 34 an exception occurs, a pointer to the last-pushed 33 EH handler block is found, and processing 32 of that "try" clause's EH cases 31 is checked. A hit on an EH case causes 30 stack cleanup to occur back to the point 29 of pushed EH, and control transfers to the 28 EH case. No hits on the EH causes the 27 next EH to be found, and the process repeats. The 26 Windows 32-bit SEH scheme is a version of 25 this.

This is a poor implementation because 24 the program pays a runtime price for each 23 try clause (push then pop) even when no 22 exception occurs.

Good implementations simply 21 record a table of ranges where try clauses 20 occur. This means there's zero overhead 19 to enter/exit a try clause. (My PARLANSE parallell 18 programming langauge uses this technique). An 17 exception looks up the PC of the exception 16 point in the table, and passes control to 15 the EH selected by the table. The EH code 14 resets the stack as appropriate. Fast and 13 pretty. I think the Windows 64 bit EH is 12 of this type, but I haven't looked carefully.

[EDIT 11 April 2020: Just measured the cost of PARLANSE 10 exceptions recently. 0nS (by design) if 9 no exception; 25ns on an 3Ghz i7 from "throw" to 8 "catch" to "acknowledge" (end 7 empty catch). OP added a link measuring 6 C++ exception handling at roughly 1000ns 5 for the simplest kind, and a literally nonStandard 4 handling scheme that clocks in at 57ns for 3 exception or no exception; CPU clock rates 2 for the C++ versions are a bit slower so 1 these numbers are only for rough comparison.]

Score: 5

The C++ standard committee published a technical 7 report on "C++ performance" to 6 debunk many myths about how C++ features 5 supposedly slow you down. This also includes 4 details about how exception handling could 3 be implemented. The draft of this technical report 2 is available for free. Check section 5.4.1. "Exception 1 Handling Implementation Issues and Techniques".

Score: 2

Asm from the Godbolt compiler explorer, for the x86-64 System V calling convention 6 with g++8.2's C++ABI, for a function that 5 catches, and one that throws.

x86-64 System 4 V uses the .eh_frame section for stack-unwind metadata, so 3 the exception-helper library functions know 2 how to walk the stack and restore registers. That's 1 what .cfi directives do.

More Related questions