Archive for September, 2010

Catch All

1 Comment »

I was using my google-fu on longjmp when I came across a page from Francesco Nidito describing how to implement a Java like try/catch exception handling in C using the CPP. Very entertaining. However, I did see the dangling ETRY; as a challenge. Can I implement a more serious try/catch without it? On top of that, can I create a syntax more elegant than the syntax of Java, Ruby and Python? I could not resist. So here is the BSD-licensed source for my version of try/catch in CPP [download .tgz]. There is one small gem, I’d like to share with those that lack the time or courage to read the source. The code below would be valid after including the try/catch header file.

try             { /* Do something. */ }
catch(DIV_ZERO) { /* Handle this. */ }
catch(*)        { printf("Can't handle %d\n", excepno); }
ensure          { if (0 == d) d = 1; }

Note the catch(*). It catches all the (hitherto) uncaught exceptions. The preprocessor expands both catch(*) and catch(22) to a correct C integer expression. Since * can mean a pointer dereference and & can mean both pointer-of and bitwise-and, the expression (arg & allones) expands to either (* & allones) or to (22 & allones). Both are a valid C expression, the first evaluating to -1 the later to 22. To distinguish between a star and a number argument, (#arg[0] == '*') is used to check the first character of the argument. I happen to think the catch all catch(*) syntax is already plenty elegant but I am very open to any improvements, so don’t hold back.