Taoffi's blog

prisonniers du temps

Throw, but only ‘exceptional’ exceptions!

I find the Try/Catch mechanism fascinating! This is probably due to some events I lived in the (not so far) History! (see below)

The thing is, when I see any of its related keywords: try, catch, finally and, specially, throw… I feel some kind of nervousness or unease!

Unfortunately, for me, more and more source code tries, catches and throws exceptions. It seems sometimes easier to throw an exception while simply an object ‘status’ would be required.

Some history

I remember an intriguing piece of code (2 or 3 C language macros) that was one of the first research I encountered about implementing a dynamic error capturing (now called ‘exception handling’). I kept this code for years (in my ‘code-museum’!) but ended up by losing it through the long journey of OS, compilers and IDEs changes!

Fortunately, I found someone (Francesco Nidito) who still (beautifully) talks about this nearly same macros (you can have a more detailed look here). His article is exactly about the solution that I first saw in the 80s, with some interesting additions (mixed with a good dose of humorJ).

 

If you used C language before, you know the impact (and importance) of ‘preprocessing’. This is the step where the compiler expands the expressions before going further in the compilation process.

For example, if you define a macro:

 

#define SAY_HELLO   int    x;\

                    for( x = 0; x < 10; x++)\

                           printf(“Hello!”);

 

In the preprocessing step, the compiler will replace each SAY_HELLO occurrence by the lines of code above.

 

longjmp And setjmp

Before diving in the historical macros, to better understand their work, we should first have a look at those two (strange) C language functions: longjmp and setjmp (declared in setjmp.h header file):

 

int setjmp(jmp_buf env);

void longjmp(jmp_buf env, int val);

 

The documentation says:

 

The setjmp function saves a stack environment, which you can subsequently restore, using longjmp. When used together, setjmp and longjmp provide a way to execute a non-local goto. They are typically used to pass execution control to error-handling or recovery code in a previously called routine without using the normal calling or return conventions.

A call to setjmp saves the current stack environment in env. A subsequent call to longjmp restores the saved environment and returns control to the point just after the corresponding setjmp call. All variables (except register variables) accessible to the routine receiving control contain the values they had when longjmp was called.

It is not possible to use setjmp to jump from native to managed code.

Note   setjmp and longjmp do not support C++ object semantics. In C++ programs, use the C++ exception-handling mechanism.

The basic Try/Catch macros

Using the magic that can be done by setjmp and longjmp, the following bizarre macros are the basis of a try/catch mechanism:

 

#define TRY            do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){

#define CATCH          } else {

#define ETRY           } }     while(0)

#define THROW          longjmp(ex_buf__, 1)

 

So, now you may write

 

TRY

{

       DoSomething(“with this string”);

}

CATCH

{

       printf(“some error happened!”);

}

ETRY         /* end of try/catch! */

 

At compile-time, this would be expanded to the following code:

 

do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){

{

       DoSomething(“with this string”);

}

} else {

{

       printf(“some error happened!”);

}

} }   while(0)           /* end of try/catch! */

 

 

What does it mean?

Let’s try to read the macros meaning:

TRY, ends with an ETRY. That is do{ xxxx } while(0) (which means: do xxxx only ONCE)

TRY starts by saving the current caller’s stack into a ‘jmp_buf’ variable. If saving the current caller stack succeeds, the next instructions (code block of ‘try’) are executed. Otherwise, the catch block instructions are executed instead.

THROW executes a non-local GOTO (by calling longjmp) which returns execution to the previous caller of the stack saved into the jmp_buf with a return value of 1 (of course, longjmp can be called with a different return value).

 

Anything new?

Of course, our C++, C# and VB Try/Catch mechanism is a little more elaborate than the one exposed here. The foundations remain the same. And, in fact, nothing had fundamentally changed in this area since: any try/catch block executes, at least, this fearful acrobatic setjmp / longjmp.

 

It may be useful to remember this before writing your next try/catch block!

 

Comments are closed