有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java异常从不在相应的try块中抛出

我有这个方法:

public int addInt(int x, int y){
    try{
        if(x<1 || y<1){
            throw new InvalidValueExeption();
        }
    } catch(InvalidValueExeption i){
        System.out.println(i);
    }
    return x+y;
}

InvalidValueExeption是一个自定义异常。所以我想测试一下:

@Test
public void test(){
    AddClass a = new AddClass();
    boolean thrown = false;

    try{
        a.addInt(-2, 3);
    } catch(InvalidValueException e){
        thrown=true;
    }

    assertTrue(thrown);
}

我无法运行此测试,因为它显示Exception exception.InvalidValueException is never thrown in the corresponding try block

我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    如果InvalidValueExeption是一个选中的异常,那么编译器会抱怨,因为addInt没有声明为throwInvalidValueExeption

    如果InvalidValueExeption不是选中的异常,那么测试将失败,因为addInt吞下了InvalidValueExeption

    你的问题中还有一个可能的拼写错误:addInt()抛出InvalidValueExeption,而test()试图抓住InvalidValueException。在前一种情况下,exception拼写为“Exeption”,在后一种情况下,exception拼写为“exception”,请注意缺少的“c”

    以下方法将起作用:

    public int addInt(int x, int y) {
        if (x < 1 || y < 1) {
            throw new InvalidValueException();
        }
    
        return x + y;
    }
    
    @Test(expected = InvalidValueException.class)
    public void test(){
        AddClass a = new AddClass();
    
        a.addInt(-2, 3);
    }