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 楼答案
如果
InvalidValueExeption
是一个选中的异常,那么编译器会抱怨,因为addInt
没有声明为throwInvalidValueExeption
如果
InvalidValueExeption
不是选中的异常,那么测试将失败,因为addInt
吞下了InvalidValueExeption
你的问题中还有一个可能的拼写错误:
addInt()
抛出InvalidValueExeption
,而test()
试图抓住InvalidValueException
。在前一种情况下,exception拼写为“Exeption”,在后一种情况下,exception拼写为“exception”,请注意缺少的“c”以下方法将起作用: