来自 3rd 方静态库的回调中未捕获的异常
我正在使用第三方库编译我的程序。如果内部发生错误,该库包含错误回调。在该错误回调中,我抛出一个异常,并且我有一个单元测试来验证当我执行无效操作时是否会抛出异常。这一切在 Windows 中都运行得很好,但是当我在 linux (fedora) 中测试它时,我因未捕获的异常而中止。
我尝试直接用 try-catch 块包装我的呼叫,但没有成功。 (另外,我的所有代码都在谷歌测试框架内运行,该框架通常也捕获异常)。唯一能捕获异常的是,如果我将 throw 语句直接包装在错误回调中的 try 块中。
有谁知道为什么会发生这种情况以及是否有办法捕获异常?
I am compiling my program with a 3rd party library. That library contains an error callback if an error occurs internally. Inside that error callback I am throwing an exception and I have a unit test to verify that when I do something invalid that the exception is thrown. This all works beautifully in Windows, but when I test this in linux (fedora) I am getting an abort from an uncaught exception.
I tried wrapping my call directly with a try-catch block but no luck. ( Also, all my code is running within the google test framework which also normally catches exceptions ). The only thing that seems to catch the exception is if I wrap the throw statement in a try block directly within the error callback.
Does anyone have any idea why this would happen and if there is a way to catch the exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您与第三方库交互时,您通常必须捕获您的代码与其代码之间边界上的所有异常:
原因是您无法确定该库是用 C++ 编写的,或者它使用与您的代码使用的 C++ 运行时版本完全相同的版本。
除非您完全确定代码可以处理您的异常,否则您无法将异常传播到第三方代码。极端的例子是 COM,其中您的代码和“其他代码”可以使用任何语言并使用任何运行时,并且不允许您让异常通过 COM 边界传播。
When you interface with third-party libraries you usually have to catch all exception on the border between your code and their code:
The reason is you can't be sure that library is written in C++ or it uses the very same version of C++ runtime as your code uses.
Unless you're completely sure that code can deal with your exceptions you can't propagate exceptions to third-party code. The extreme example is COM where both your code and "other code" can be in whatever language and with whatever runtime and you are not allowed to let exceptions propagate through COM boundary.
通常,您不应该“通过”您不了解的代码抛出异常。它可能是 C 代码,它甚至不会自行清理。
如何处理您的具体问题需要有关您正在交互的第三方库的具体信息。那个回调是做什么用的?给你一个修复问题的机会?通知您发生了错误?您可以取消调用它的任何操作吗?
处理这种情况的一种方法是在调用回调时在某处存储一些信息,并在调用该库的函数完成实际处理时检查该信息。
Usually you should not throw exceptions "through" code you do not know anything about. It might be C code, which will not even clean up after itself.
How to deal with your concrete problem would require concrete information about the 3rd-party library you are interfacing with. What is that callback there for? To give you a chance to fix stuff? To inform you that an error occurred? Can you cancel whatever operation it is called from?
One way to deal with such a scenario is to store some information somewhere when the callback is called and check for that information when the actual processing finishes from your function that calls into that library.