java.lang.ClassCastException with null message and cause

时间:2016-11-09 08:24:51

标签: java null message classcastexception

I work on a project using Java 8

We have a negative test similar to this:

public Integer g(Object data)
{
    try
    {
        Double d = (Double)data;
    }
    catch(ClassCastException ex)
    {
        if( ex.getMessage() == null )
        {
            return 1;
        }
    }
    return 0;
}

@Test
public void h()
{
    Integer count = 0;
    for( Integer idx = 0; idx < 100000; idx++ )
    {
        // The test
        count += g(0.7312345f);
    }
    System.out.println("Total ClassCastException's with null message: "+count);
}

The negative test expects the exception java.lang.ClassCastException with message "java.lang.Float cannot be cast to java.lang.Double" and it sometimes gets null message

I tried to debug it in eclipse but somehow when attached to debugger the exception and message were as expected all the time

1 个答案:

答案 0 :(得分:5)

在OpenJDK 8中运行AxelH给出的完整示例,我发现我怀疑是正确的。

复制,所以它不会消​​失(他说他会删除):

public class Main{

    int cnt = 0, cntNull = 0;
    public static void main(String[] args) { 
        new Main().test();
    }

    public void test(){
        for( Integer idx = 0; idx < 200000; idx++ )
        {
            loseType(0.45642f, idx);
        }
        System.out.println(cnt + " error");
        System.out.println(cntNull + " null");
    }

    public void loseType(Object data, Integer i){
        try{
            gainType((Double)data);
        } catch(ClassCastException e){
            cnt++;
            if(e.getMessage() == null){
                cntNull++;
            }
        }
    }

    public void gainType(Double x){

    }
}

使用javac Main.java进行编译,然后使用java -Xmixed Main运行(与默认java Main相同),并且您的异常通常会显示空消息。使用java -Xint Main运行它,它永远不会null

原因是在混合模式下它使用运行时解释器直到编译类,然后转移到它,但使用-Xint使它始终使用解释器,其中消息始终存在。似乎编译的本机代码有一个错误,它会在没有正确消息的情况下创建异常。