gpt4 book ai didi

c++ - 无法捕获异常!

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:13 30 4
gpt4 key购买 nike

我正在使用 swig 用 python 包装来自 C++ 库的类。它总体上工作,但有一个从库中抛出的异常,我似乎无法在 swig 接口(interface)中捕获它,所以它只会使 python 应用程序崩溃!

PyMonitor.cc 类描述了所需类 Monitor 的 swig 接口(interface)。如果连接失败,Monitor 的构造函数将抛出异常。我想在 PyMonitor 中处理这个异常,例如:

PyMonitor.cc:

#include "Monitor.h"  

// ...

bool PyMonitor::connect() {
try {
_monitor = new Monitor(_host, _calibration);
} catch (...) {
printf("oops!\n");
}
}

// ...

但是,connect() 方法永远不会捕获异常,我只会收到“在抛出...后调用终止”错误,然后程序中止。

我不太了解 swig,但在我看来,这一切都很好,C++ 异常应该在终止程序之前传播到 connect() 方法。

有什么想法吗?

最佳答案

如果你想在那里解析它们,你必须将异常转发给 Python。查看SWIG Documentation .为了转发异常,您只需在 SWIG 接口(interface) (.i) 文件中添加一些代码。基本上,这可以在 .i 文件中的任何位置。

应在此处指定所有类型的异常,SWIG 捕获列出的异常类型(在本例中为 std::runtime_error、std::invalid_argument、std::out_of_range),所有其他异常被捕获为未知异常(因此被正确转发!)。

// Handle standard exceptions.
// NOTE: needs to be before the %import!
%include "exception.i"
%exception
{
try
{
$action
}
catch (const std::runtime_error& e) {
SWIG_exception(SWIG_RuntimeError, e.what());
}
catch (const std::invalid_argument& e) {
SWIG_exception(SWIG_ValueError, e.what());
}
catch (const std::out_of_range& e) {
SWIG_exception(SWIG_IndexError, e.what());
}
catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}

关于c++ - 无法捕获异常!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913396/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com