Question

I am writing an exception handling library in C and i ran into a bump:

#define TRY do{ jmp_buf ex_buf__; switch( setjmp(ex_buf__) ){ case 0:
#define FINALLY break; } default:
#define CATCH(x) break; case x:
#define ETRY } }while(0)
#define THROW(x) longjmp(ex_buf__, x)

In my current implementation of try catch throw, I won't be able to throw an exception from inside a method called from inside the try block because the jmp_buf variable is local. How would i make that possible? I thought about a global variable but that would not allow me to have nested try catch blocks.

Was it helpful?

Solution

You need to use a global jump buffer, because it needs to be visible to your "clients". You could, for example, save the old jump buffer in a try block, and restore it after its use.

In general, I would not recommend this approach at all, though. Trying to retrofit features into a language is fraught with peril, not the least of which would be the following code:

for ;; { 
  TRY {
    if (someVar) {
      break;
    }
  }
  FINALLY {
    doIt()
  }
  ETRY
}

OTHER TIPS

Use a stack of jmp_buf's. Or better yet, use the existing CII library, which has been designed, built, and tested for this purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top