Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 place than return codes. I would appreciate if there are some leads on how to do this.

I am particularly concerned with resource cleanup being correctly done if any such error occurs.

Also how do I handle errors that result in multi-threaded programs using them?

Even better, is there some C library that already exists for error/exception handling?

like image 379
dubnde Avatar asked May 04 '09 12:05

dubnde


2 Answers

If you are worried about resource cleanup, you have to seriously wonder whether longjmp() and setjmp() are a good idea.

If you design your resource allocation system so that you can in fact clean up accurately, then it is OK - but that design tends to be tricky, and typically incomplete if, in fact, the standard libraries that your code uses themselves allocate resources that must be released. It requires extraordinary care, and because it is not wholly reliable, it is not suitable for long-running systems that might need to survive multiple uses of the setjmp()/longjmp() calls (they'll leak, expand, and eventually cause problems).

like image 187
Jonathan Leffler Avatar answered Oct 28 '22 11:10

Jonathan Leffler


Have a look at this example/tutorial:
http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html

like image 36
eaanon01 Avatar answered Oct 28 '22 13:10

eaanon01