我有以下代码:
TestClass test=new TestClass();
test.setSomething1(0); //could, but probably won't throw Exception
test.setSomething2(0); //could, but probably won't throw Exception
我想执行:test.setSomething2(0);
即使 test.setSomething(0)
(上面的行)抛出异常。有没有其他方法可以做到这一点:
try{
test.setSomething1(0);
}catch(Exception e){
//ignore
}
try{
test.setSomething2(0);
}catch(Exception e){
//ignore
}
我有很多连续的 test.setSomething,它们都可能抛出异常。如果他们这样做,我只想跳过该行并转到下一行。
澄清一下,我不关心它是否抛出异常,而且我无法编辑抛出该异常的代码的源代码。
这是一个我不关心异常的案例(请不要使用像“你永远不应该忽略异常”这样的普遍量化的陈述)。我正在设置一些对象的值。当我将这些值呈现给用户时,无论如何我都会进行空值检查,因此是否执行任何代码行实际上并不重要。
最佳答案
try {
// Your code...
} catch (Exception ignore) { }
在 Exception
关键字之后使用单词 ignore
。
关于java - 如何忽略 Java 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659462/