Search code examples
cexceptiontry-catchsetjmp

Exception handling in C - making try catch work across functions


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.


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
    }