SWIG和例外:避免在C++中使用throw(Exception)

SWIG & exceptions: avoid using throw(Exception) in C++

本文关键字:throw Exception C++ SWIG      更新时间:2023-10-16

我正在使用SWIG将c++库包装成JAVA库,下面的想法来自通过SWIG处理JAVA中的c++异常。

我已经能够包装我所有的异常,但是如果一个函数启动一个异常没有明确地告诉在c++声明中,JAVA代码不工作。例子:如果我做

class A {
    public:
         void f () throw (MyException){};

一切顺利。但是,如果我这样做

class A {
    public:
         void f (){};

当我在JAVA中使用代理类

捕获异常时
try {
     // this is the proxy wrapped (java) class
     A.f();
}
catch(MyException e)
{
    ...
}

JAVA编译失败,出现以下错误

exception MyExceptionn is never thrown in body of corresponding try statement

我不想在我的c++代码中使用异常通知,如果我可以避免http://www.gotw.ca/publications/mill22.htm。问题是,我能避免吗?如何?

让MyExtension扩展RuntimeException而不是Exception,那么它就可以从任何函数中抛出,而不仅仅是从显式声明了抛出子句的函数中抛出。

static class MyException extends RuntimeException {
}

static void f() {
    throw new MyException();
}

try {
    f();
} catch(MyException e) {
}