How Exceptions Work Behind the Scenes in C
Introduction:
Exceptions are often questioned for their efficiency. This article explores the intricate workings of exceptions in C to provide a comprehensive understanding of their execution process.
Exception Handling Mechanism:
Exceptions are not directly akin to repeatedly executing returns; they involve an additional layer of exception tables. When an exception is thrown, the compiler generates a call to __cxa_throw, which utilizes these tables to find the handler and unwind the stack until it reaches the appropriate handler.
Throwing an Exception:
Throwing an exception requires significant runtime overhead because:
Exceptional Returns:
In contrast, returning a value incurs minimal overhead. Exceptions should be utilized sparingly, only for exceptional scenarios.
Example Code:
The following simplistic C code illustrates the instruction generation for exception handling:
<code class="cpp">class MyException { public: MyException() { } ~MyException() { } }; void my_throwing_function(bool throwit) { if (throwit) throw MyException(); } void another_function(); void log(unsigned count); void my_catching_function() { log(0); try { log(1); another_function(); log(2); } catch (const MyException& e) { log(3); } log(4); }</code>
Generated Assembly:
Compiling this code with GCC on Linux resulted in the following assembly output:
Throwing an Exception:
_Z20my_throwing_functionb: ... movl , (%esp) call __cxa_allocate_exception ... movl %eax, (%esp) call __cxa_throw ...
Exception Handling Table:
.section .gcc_except_table,"a",@progbits .LLSDATT9: ... .uleb128 .LEHB1-.LFB9 .uleb128 .LEHE1-.LEHB1 .uleb128 .L12-.LFB9 .uleb128 0x1 ...
Conclusion:
Exceptions require substantial overhead for handling and unwinding, while return values incur minimal expense. Exceptions are optimal for exceptional scenarios, but should be used judiciously to avoid performance degradation.
The above is the detailed content of How Do Exceptions Operate Internally in C ?. For more information, please follow other related articles on the PHP Chinese website!