Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I throw C++ exceptions from legacy C callbacks?

I have C++ code that uses some C libraries. The C libraries take C language callbacks. I wrote a callback in my C++ code and now I somehow need to report error from it (but it returns void). I wonder if I can throw an exception from a C callback that is used from C++ code?

This is very difficult for me to understand.

Thanks, Boda Cydo.

like image 922
bodacydo Avatar asked Jul 05 '10 02:07

bodacydo


People also ask

Can you throw exceptions in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

What happens when exception is thrown CPP?

When an exception occurs within the try block, control is transferred to the exception handler. If no exception is thrown, the code continues normally and the handlers are ignored. An exception in C++ is thrown by using the throw keyword from inside the try block.


2 Answers

Yes, you should be able to do so. However, keep in mind it's entirely likely that the C library was not written to be exception safe, and as a result you might leave some of that library's structures in some inconsistent state. It depends entirely on the specific library and on the specific callback function. If nothing else, that library would probably have to be written with C++ support in mind from the beginning with respect to that callback.

like image 75
Billy ONeal Avatar answered Oct 27 '22 01:10

Billy ONeal


Yes, you could throw an exception from your C++ function. However, it can only be caught by C++ code so it won't be handled in the legacy library.

like image 21
Anthony Avatar answered Oct 27 '22 02:10

Anthony