Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exception propagation in externally linked C libraries

I am writing a C++ library that uses an external third party C library. So my library will call functions in this third party library and the third party library will call back into a different part of my library.

I am wondering what happens to exceptions in this case? Say MyLib::foo() calls external C library function which eventually calls MyLib::bar(), and bar throws an exception, what happens? Will the exception be correctly propagated to a handler in foo() ?

Thanks!

like image 914
aaa Avatar asked Feb 25 '23 13:02

aaa


2 Answers

Will the exception be correctly propagated to a handler in foo()?

I think whether exceptions propagate through external C code is undefined. What's even worse, the C code is unprepared and unable to handle the exception. C code doesn't need to immune against sudden, unexpected returns, so it knows no RAII etc.

When I was once faced with such a situation, I caught the exception before returning to the C API, stored it, and re-threw it once the call came back from the C API.

like image 63
sbi Avatar answered Mar 08 '23 04:03

sbi


It is a heavy platform implementation detail. In general, the exception plumbing is somewhat likely to be able to unwind the stack through C function activation frames. Necessary because the CRT is often written in C. However, the C code is pretty unlikely to be happy about it, state got mutated that cannot be restored.

Just in case this is Windows, the C code does have a shot at it. C++ exceptions are piggy-backed onto the generic exception support built into Windows, called Structured Exception Handling (SEH). You use the __try and __except keywords to call an exception filter that can restore the C code state. Obviously this is not portable.

Never ask an implementation detail question without mentioning the implementation details, please.

like image 41
Hans Passant Avatar answered Mar 08 '23 05:03

Hans Passant