c++中有类似Java的吗

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

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


当前回答

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 (...) {
    // ...
}

将捕获所有c++异常,但它应该被认为是糟糕的设计。你可以使用c++11新的current_exception机制,但是如果你没有能力使用c++11(遗留代码系统需要重写),那么你就没有命名异常指针来获取消息或名称。您可能希望为可以捕获的各种异常添加单独的catch子句,并且只捕获底部的所有内容以记录意外异常。例如:

try{
    // ...
} catch (const std::exception& ex) {
    // ...
} catch (const std::string& ex) {
    // ...
} catch (...) {
    // ...
}

可以这样写:

try
{
  //.......
}
catch(...) // <<- catch all
{
  //.......
}

但是这里有一个非常不明显的风险:您无法找到try块中抛出的错误的确切类型,因此当您确定无论异常类型是什么,程序都必须以catch块中定义的方式持续存在时,可以使用这种catch。

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

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

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

(在c++中)以可移植的方式捕获所有异常是不可能的。这是因为在c++上下文中,有些异常并不是异常。这包括除以零误差等。可以通过破解来获得在这些错误发生时抛出异常的能力,但这并不容易做到,当然也不容易以一种可移植的方式得到正确的处理。

如果你想捕获所有的STL异常,你可以这样做

try { ... } catch( const std::exception &e) { ... }

这将允许您使用e.what(),它将返回一个const char*,它可以告诉您有关异常本身的更多信息。这是与Java构造最相似的构造。

如果有人愚蠢地抛出一个不继承std::exception的异常,这将对您没有帮助。

通用的异常捕获机制 会非常有用。

表示怀疑。你已经知道你的代码坏了,因为它崩溃了。进食异常可能会掩盖这一点,但这可能只会导致更糟糕、更微妙的错误。

你真正需要的是一个调试器……