简体   繁体   中英

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.

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM