简体   繁体   中英

catch exception on pure C without try-catch mechanism

I need to create a dump file when there is an exception.

Is it possible to do so without using __try{...} and __except(e){...} ?

Is there a way to create a callback function or register an action waiting for a system crash?

Thanks in advance.

是的,您可以使用signal来注册特定信号的回调,包括异常。

The basic function of exception handling is to transfer control to an exception-handler when an error occurs, where the handler resides somewhere higher up in the current function call hierarchy. Standard C has a mechanism to accomplish this: setjmp() and longjmp(). This and this are two good articles that speak about exception handling in C. If you work with Microsoft Visual C look the try-except statement an extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur.

If you want to implement your own exception-style handling in C, there is setjmp() and friends , but beware this is black magic and a good way of shooting yourself in the foot if you are not careful.

For other errors it depends what you mean by "exception". I can think that you either mean an error when calling a library function (in which case you should be checking the return values appropriately) or a SEGV, in which case you are going to get a SIGSEGV and your process will die shortly afterwards. You can write a signal handler to use backtrace() to give you a clue, but not much more than that.

Program or system crashes are generally something outside the perview of C. You have to look into your OS's facilities for detetcting and handling such things (which of course would be OS-dependent).

For "exceptions" in a general sense, the typical idiom in old C to perform exception handling was with goto . You put a label past your return statement to act as the "exception handler", and any call that detects and exceptional condition goto s that label.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM