Throwing out from a C ++ function called by a C function using pointer dereferencing

Consider the following function defined in the C library:

void f(void (*callback)(int)) { callback(0); } 

which is called from a C ++ 11 program that defines callback() , possibly throwing an exception, as shown below:

 void callback(int) { /* can I throw ? */} try { f(callback); } catch (...) { /* can the exception be caught ? */ } 

My questions:

  • Does this standard allow callback to be called when called from f() ? If not, should / should declare callback() a noexcept ?
  • If so, does the standard support to exclude an exception object?
+5
source share
1 answer

Below the source code can be compromised.

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 is launched, an exception will be thrown and the program will unwind the stack, trying to find the catch block, but it cannot. Then an interrupt occurs:

 #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 the cpp function that returns expc in c, but you can never put a catch block in c because it does not compile.

How is the C ++ exception handling runtime implemented? This explains how the exception works in C ++.

I really don't think throwing throw exception in c would be something good, since you can't do anything with it in the “normal” way.

+1
source

Source: https://habr.com/ru/post/1201137/


All Articles