为什么我在运行java程序时会收到此消息?

时间:2012-05-09 09:50:22

标签: java c++ java-native-interface

Java代码:

package Package;

public class MyExceptionTester {

private native void compute() throws Exception;

public static void main(String... args) {
    try {
        MyExceptionTester met = new MyExceptionTester();
        met.compute(); // This method will throw an exception which gets printed from the catch block
    } catch(Exception exc) {
        System.out.println("From Java :" + exc);
    }
}

static {
    System.loadLibrary("MyExceptionTester");
 }
}

C ++代码:

#include "iostream"
#include "Package_MyExceptionTester.h"

void Java_Package_MyExceptionTester_compute
   (JNIEnv *env, jobject obj) {
        jthrowable exc;
        try {
            jint i = 1/0;
            throw "C++ Message : Hey ! Can't Divide By Zero";
        } catch(char *str) {
            jclass excClass = env->FindClass("java/lang/Exception");
            if(excClass == NULL) {
                    return;
                }
            env->ThrowNew(excClass,str);
          }

}

当我在包含dll后运行java程序时,我收到以下消息:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_INT_DIVIDE_BY_ZERO (0xc0000094) at pc=0x65c4121a, pid=5292, tid=6000 
#
# JRE version: 7.0
# Java VM: Java HotSpot(TM) Client VM (20.0-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# C  [MyExceptionTester.dll+0x121a] 
#
# An error report file with more information is saved as:
# W:\elita\jnitesters\workspace\java\JNI\build\classes\hs_err_pid5292.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

为什么我会收到此消息?为什么我看不到输出应该是从java catch 块打印的消息。

2 个答案:

答案 0 :(得分:2)

 jint i = 1/0;
 throw "C++ Message : Hey ! Can't Divide By Zero";

由于程序在throw语句之前崩溃,因此try/catch块不会捕获此异常。除0之外的划分也不例外。

也许可能会有所帮助:

int d = 0;
jthrowable exc;
try 
{
    if ( d == 0 )
        throw "C++ Message : Hey ! Can't Divide By Zero";
    jint i = 1/d;
} catch(char *str) 
{
    jclass excClass = env->FindClass("java/lang/Exception");
    if(excClass == NULL) 
    {
       return;
    }
    env->ThrowNew(excClass,str);
}

答案 1 :(得分:-1)

本机代码调用已在JVM中。由于本机程序在抛出异常之前崩溃,因此本机程序中的崩溃也会导致JVM崩溃。