How do I implement exceptions with nestable try-catch-finally statement with messages in C
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-ca开发者_运维问答tch-else exceptions, they are not nestable. I'm also hoping to add messages to the exceptions. Any idea how I might be able to do it?
Dave Hanson has already done a really nice package of exception macros as part of his excellent book C Interfaces and Implementations. You could either use the code wholesale or learn from his techniques. For anyone who does a fair amount of C programming, the book is worth buying—it will change the way you change about C programming, and it will show you how to do object-oriented design in C.
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++?
Well, you cannot really implement exceptions in C since they are not supported by the language. The best you can do is emulate them using setjmp
and longjmp
and some diabolically clever macros.
A quick search turns up these links that may be useful to you:
- Exceptions in C
- Exception handling with longjmp()
精彩评论