How to implement exceptions using nested try-catch-finally commands with messages in C

I am looking to implement exceptions using a nested try-catch-finally statement with C messages using longjmp / setjmp.

I managed to implement try-catch-else exceptions, they are not nested. I also hope to add posts to the exceptions. Any idea how I can do this?

+5
c
source share
3 answers

Dave Hanson has already made a really nice package of exception macros as part of his excellent book C Interfaces and Implementations . You can either use the code in bulk or learn from its methods. For those who do enough C programming, the book is worth buying, so it will change the way you change C programming and show you how to make an object-oriented design in C.

+4
source share

For nesting: the frame stack of existing try / catch blocks.

Your attempt will use setjmp to save to jmpbuffer (I think). If you made a try and, therefore, are now within the try block and click another try, then you want to save the existing jmpbuffer, as well as create a new one - Push - and when you catch, you return to the point of the most recent attempt for a long time, so you pop the latest jmpbuffer. So I think a stack-like model makes sense for a nested try / catch.

For implementation, I think the easiest apporach is to reserve an array of jmpbuffers, therefore, limiting the capture depth of try, but keeping it simple; Push and Pop just require you to keep track of the index in this array.

For messages and other exception contents, the reserved area for "currentException".

Content Exclusion. Keep it simple, define an Exception structure. A char array and int. Keeping it simple but not too simple, reserve an array of them to maintain the chain.

For the cast you allow

throw ( "string", errcode ) 

which just zeros the structure of the array and makes one entry. AND

  catch ( exception ) 

Now you can look in the array and find the first record, and then

  throwChain ( "string", errcode) 

Which adds a new exception to the array (if there is room, and if it cannot shuffle the array by some rule, for example FIFO)

But I have to ask, why not just use C ++?

+3
source share

Well, you really cannot implement exceptions in C, as they are not supported by the language. The best you can do is emulate them with setjmp and longjmp and some mentally delicate macros.

A quick search opens these links that may come in handy:

+2
source share

All Articles