如何忽略Java中的异常

Nic*_*ick 15 java exception-handling exception

我有以下代码:

TestClass test=new TestClass();
test.setSomething1(0);  //could, but probably won't throw Exception
test.setSomething2(0);  //could, but probably won't throw Exception
Run Code Online (Sandbox Code Playgroud)

我想执行:test.setSomething2(0);即使test.setSomething(0)(它上面的行)抛出异常.有没有办法做到这一点以外:

try{
   test.setSomething1(0);
}catch(Exception e){
   //ignore
}
try{
   test.setSomething2(0);
}catch(Exception e){
   //ignore
}
Run Code Online (Sandbox Code Playgroud)

我有很多test.setSomething连续,所有这些都可以抛出异常.如果他们这样做,我只想跳过那一行并转到下一行.

为了澄清,我不在乎它是否抛出异常,我无法编辑抛出此异常的代码的源代码.

这是我不关心例外的情况(请不要使用普遍量化的陈述,例如"你永远不应忽视异常").我正在设置一些Object的值.当我向用户呈现值时,无论如何我都会进行空检查,因此如果执行任何代码行并不重要.

Mar*_*nik 20

我会严重怀疑任何测试代码的完整性,它忽略了测试代码抛出的异常.那就是说,假设你知道自己在做什么......没有办法从根本上忽略抛出的异常.您可以做的最好的事情是最小化包含异常抛出代码所需的样板.

如果您使用的是Java 8,则可以使用:

public static void ignoringExc(RunnableExc r) {
  try { r.run(); } catch (Exception e) { }
}

@FunctionalInterface public interface RunnableExc { void run() throws Exception; }
Run Code Online (Sandbox Code Playgroud)

然后,并暗示静态导入,您的代码变为

ignoringExc(() -> test.setSomething1(0));
ignoringExc(() -> test.setSomething2(0));
Run Code Online (Sandbox Code Playgroud)


Joe*_*ore 14

try {
 // Your code...
} catch (Exception ignore) { }
Run Code Online (Sandbox Code Playgroud)

使用关键字ignore后面的Exception字词.

  • 是的,但Lint会忽略它,所以你不会得到警告 (9认同)
  • ignore是您为Exception指定的名称,您给出的名称无关紧要 (8认同)

小智 7

IntelliJ Idea IDE 建议将变量重命名为ignored

当它不被使用时。

这是我的示例代码。

try {
    messageText = rs.getString("msg");
    errorCode = rs.getInt("error_code");
} catch (SQLException ignored) { }
Run Code Online (Sandbox Code Playgroud)