How do I implement exceptions with nestable try-catch-finally statement with messages in C

后端 未结 3 924
萌比男神i
萌比男神i 2021-01-03 04:10

I\'m looking to implement exceptions with nestable try-catch-finally statement with messages in C using longjmp/setjmp.

I\'ve managed to implement try-catch-else exc

3条回答
  •  梦毁少年i
    2021-01-03 04:59

    For nesting: a stack-frame of current try/catch blocks.

    Your try will be using setjmp to save to a jmpbuffer (I guess). If you've done a try, and hence are now in the scope of a try block and hit another try then you want to preserve the existing jmpbuffer and also create a new one - Push - and when catching you are longjmp-ing back to the point of the most recent try hence you Pop the latest jmpbuffer. So I think a stack-like model make sense for nested try/catch.

    For implementation, I guess the simplest apporach is to reserve an array of jmpbuffers, hence limiting your try catch depth - but keeping it simple; Push and Pop just require you to track the index in that array.

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

    Exception content. Keep it simple, define an Exception struct. A char array and an int. Keeping it simple, but not too simple, reserve an array of them so that you can support chaining.

    For a throw you allow

     throw  ( "string", errcode )
    

    Which simply zeros the array structure and makes one entry. And

     catch ( exception )
    

    Now can look in the array and finds the first entry, and then

     throwChain ( "string", errcode)
    

    Which adds the new exception to the array (if there is room, and if not can shuffle the array according some rule such as FIFO)

    But, I've got to ask, why not just use C++?

提交回复
热议问题