What are some “good” ways to use longjmp/setjmp for C error handling?

前端 未结 6 1041
南旧
南旧 2020-12-24 14:09

I have to use C for one project and I am thinking of using longjmp/setjmp for error handling as I think it will be much easier to handle error in one central pl

6条回答
  •  伪装坚强ぢ
    2020-12-24 14:15

    Symbian implemented it's Leave mechanism in terms of longjmp() and this serves as a good walk through of all the things you need to do.

    Symbian has a global 'cleanup stack' that you push and pop things you want cleaned up should an jump happened. This is the manual alternative to the automatic stack unwinding that a C++ compiler does when a C++ exception is thrown.

    Symbian had 'trap harnesses' that it would jump out to; these could be nested.

    (Symbian more recently reimplemented it in terms of C++ exceptions, but the interface remains unchanged).

    All together, I think that proper C++ exceptions are less prone to coding errors and much faster than rolling your own C equivalent.

    (Modern C++ compilers are very good at 'zero overhead' exceptions when they are not thrown, for example; longjmp() has to store the state of all the registers and such even when the jump is not later taken, so can fundamentally never be as fast as exceptions.)

    Using C++ as a better C, where you only adopt exceptions and RAII, would be a good route should using longjmp() for exception emulation be tempting to you.

提交回复
热议问题