Consider the following function defined in a C library:
void f(void (*callback)(int)) { callback(0); }
which will be called from a C++11 program defining callback()
, possibly throwing an exception, as below:
void callback(int) { /* can I throw ? */}
try {
f(callback);
} catch (...) {
/* can the exception be caught ? */
}
My questions are:
f()
? If not, must/should I declare callback()
with the noexcept
specifier?Below source code can be compliled.
exception.cpp:
extern "C"
void throwInCPP() {
throw 5;
}
main.c
#include <stdio.h>
void throwInCPP();
void throwExp(void (*callback)()) {
callback();
}
int main() {
throwExp(throwInCPP);
return 0;
}
When when it gets ran, exception will be thrown and the program unwind the stack try to find a catch block but it cannot. Then abort happens:
#0 0x00007ffff7238d67 in raise () from /usr/lib/libc.so.6
#1 0x00007ffff723a118 in abort () from /usr/lib/libc.so.6
#2 0x00007ffff7b2e1f5 in __gnu_cxx::__verbose_terminate_handler() ()
from /usr/lib/libstdc++.so.6
#3 0x00007ffff7b2c076 in ?? () from /usr/lib/libstdc++.so.6
#4 0x00007ffff7b2c0c1 in std::terminate() () from /usr/lib/libstdc++.so.6
#5 0x00007ffff7b2c2d8 in __cxa_throw () from /usr/lib/libstdc++.so.6
#6 0x00000000004007fa in throwInCPP ()
#7 0x00000000004007bd in throwExp (callback=0x4007d4 <throwInCPP>) at main.c:6
#8 0x00000000004007cd in main () at main.c:11
I think you can always call a cpp function which throws an expection in c, but you can never put a catch block in c since it doesn't compile.
How is the C++ exception handling runtime implemented? This explains how does the exception work in c++.
I don't really think throw exception in c will be something good since you cannot do anything with it in the "normal" way.
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