[Cfp-interest] another look at try/catch

David Hough CFP pcfp at oakapple.net
Thu May 29 12:16:00 PDT 2014


Try Catch for C

Being dissatisfied with the pragma and macro approaches to exception
handling in C, let's see what we can usefully glean from C++:


try {
 /* compound statement */
 throw ex   /* generate exception of type of ex */
 or
 generate standard exception
}
catch (t e) {
 /* exceptional case code for thrown expression e of type t */
}
catch (exception& e) {
 /* exceptional case code for standard exception e */
}
catch (...) {
 /* all other exceptional cases */
}

In the nonexceptional exit from the try block, the catch blocks are
skipped.

This is more than we need, but it does allow a hierarchy of exception
handling where wanted.    C++ is thinking in terms of standard exceptions
like bad_alloc that are always defined and enabled, and user-defined
exceptions that are enabled when thrown and caught.

Our floating-point exceptions have a default handling that does not
invoke any catch code.     We need to enable such catching when necessary
by mentioning
the exception in the proper scope.     So the code generation for the
try block needs to be aware of all the nested exception handling that
is staticly visible.

Furthermore it is often the case that more than one exception will be
handled by a catch clause - overflow and underflow being examples.
So to prevent accidentally attempting to port unsupported code from C++ to C,
I'd suggest that we define catch_fe_excep and catch_fe_flag
rather than catch.

catch_fe_excep( e exceptionlist) { }
 catches the listed exceptions as soon as possible - nondeterministically -
 traps are an acceptable implementation - and executes the catch block
 e has the value of the caught exception

catch_fe_flag(f flaglist) { }
 catches the listed flags when the try block exits normally if they have
 been raised during the try block - deterministically - and executes the
 catch block
 f has the value of the caught flags

I don't think this would get in the way of a future
C committee that might decide to have adopt full C++ try/catch.
The syntax seems nicer, or at least more familiar, 
than the macro or pragma syntax.
I'd suppose that the C committee would find it more acceptable.

The details of the syntax and semantics have lots of room for adjustment.
We could make it look more like C++ by having just the "catch" keyword
and special macros to make a "type" out of an exceptionlist or flaglist.
Then the syntax would look like

catch( FE_EXCEP_LIST_TYPE(e1,e2,e3...), e)
or
catch( FE_FLAG_LIST_TYPE(f1,f2,f3,...), f)


Semantic issues include whether to allow nesting and what happens to
uncaught exceptions and untested flags.

It doesn't address presubstitution, which remains a tough nut to crack.



More information about the Cfp-interest mailing list