c++中有类似Java的吗

try {
    ...
}
catch (Throwable t) {
    ...
}

我试图调试Java/jni代码调用本机windows函数和虚拟机不断崩溃。本机代码在单元测试中表现良好,只有在通过jni调用时才会崩溃。一个通用的异常捕获机制将被证明是非常有用的。


当前回答

这取决于编译器环境。 GCC不捕获这些。 Visual Studio和我之前用的Borland。

因此,关于崩溃的结论是,它取决于开发环境的质量。

c++ 规范说catch(…)必须捕获任何异常,但它不是在所有情况下都捕获。

至少我是这么想的。

其他回答

Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead. Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc? Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface. There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)

请注意

try{
// ...
} catch (...) {
// ...
}

仅捕获语言级异常,其他低级异常/错误,如访问违反和分割错误不会被捕获。

try {
   // ...
} catch (...) {
   // ...
}

注意…catch里面是一个真正的省略号。三个点。

然而,由于c++异常不一定是基Exception类的子类,因此在使用此构造时无法实际看到抛出的异常变量。

这取决于编译器环境。 GCC不捕获这些。 Visual Studio和我之前用的Borland。

因此,关于崩溃的结论是,它取决于开发环境的质量。

c++ 规范说catch(…)必须捕获任何异常,但它不是在所有情况下都捕获。

至少我是这么想的。

这是如何从catch(…)中反向工程异常类型,如果你需要(可能有用时,从第三方库捕获未知)使用GCC:

#include <iostream>

#include <exception>
#include <typeinfo>
#include <stdexcept>

int main()
{
    try {
        throw ...; // throw something
    }
    catch(...)
    {
        std::exception_ptr p = std::current_exception();
        std::clog <<(p ? p.__cxa_exception_type()->name() : "null") << std::endl;
    }
    return 1;
}

如果你有能力使用Boost,你可以让你的捕捉部分更简单(在外部),并具有跨平台的潜力

catch (...)
{
    std::clog << boost::current_exception_diagnostic_information() << std::endl;
}