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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With