eladyanai
eladyanai

Reputation: 1093

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.

Upvotes: 2

Views: 367

Answers (4)

gliderkite
gliderkite

Reputation: 8928

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.

Upvotes: 2

blueshift
blueshift

Reputation: 6882

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.

Upvotes: 1

T.E.D.
T.E.D.

Reputation: 44804

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 gotos that label.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

Yes, you can use signal to register a callback for a specific signal, including exceptions.

Upvotes: 3

Related Questions