Before C11 implementing try/throw/catch
clauses with C alone was difficult. C lacked three features for that. First, there was no clear concept of threads. A throw
that wants to unwind the stack to a calling function would have to capture the nearest try
clause on the stack by inspecting a global variable. If you are running in a threaded environment (which most people do theses days) this global variable would have to hold the state of all current try
clauses of all threads. With the new feature of _Thread_local
variables (or their emulation through P99_DECLARE_THREAD_LOCAL
in P99) this is now easy to solve. We just need a thread local variable that implements a stack of states.
The second feature that is useful for such an implementation are atomic operations. Though we can now implement a thread local variable for the stack of states, we still have to be careful that updates of that variable are not interrupted in the middle by signal handlers or alike. This can be handled with atomic operations, P99 also emulates the _Atomic
feature on common platforms.
The third ingredient is _Noreturn
. For C11 we can specify that a certain function will never return to the caller. This enables the compiler to emit more efficient code for if a branch in an execution ends with such an noreturn
function.
These three interfaces together with other features that had been already present in P99, made it straight forward to implement P99_TRY
, P99_THROW
, P99_CATCH
and P99_FINALLY
.
Continue reading “try, throw and catch clauses with P99”
You must be logged in to post a comment.