如何忽略Java中的异常 [英] How to ignore Exceptions in Java

查看:1784
本文介绍了如何忽略Java中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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)(上面的行)会引发异常。有没有办法做到这一点除了:

I would like to execute: test.setSomething2(0); even if test.setSomething(0) (the line above it) throws an exception. Is there a way to do this OTHER than:

try{
   test.setSomething1(0);
}catch(Exception e){
   //ignore
}
try{
   test.setSomething2(0);
}catch(Exception e){
   //ignore
}

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

I have a lot of test.setSomething's in a row and all of them could throw Exceptions. If they do, I just want to skip that line and move to the next one.

为了澄清,我不在乎它是否抛出异常,我可以不要编辑引发这个异常的代码的源代码。

For clarification, I don't care if it throws an Exception, and I can't edit the source code of the code which throws this exception.

这是一个我不关心例外的情况(请不要使用普遍量化的语句,如你不应该忽视异常)。我正在设置一些Object的值。当我向用户呈现值时,我会执行null检查,所以如果执行任何代码行,实际上并不重要。

THIS IS A CASE WHERE I DON'T CARE ABOUT THE EXCEPTIONS (please don't use universally quantified statements like "you should never ignore Exceptions"). I am setting the values of some Object. When I present the values to a user, I do null checks anyway, so it doesn't actually matter if any of the lines of code execute.

推荐答案

我会非常怀疑任何测试代码的理智,它忽略了测试代码抛出的异常。也就是说,假设你知道你正在做什么...没有办法从根本上忽略抛出的异常。最好的方法是最小化包装异常抛出代码所需的样板。

I would gravely doubt the sanity of any testing code which ignores exceptions thrown from tested code. That said, and assuming that you know what you are doing... there is no way to fundamentally ignore a thrown exception. The best that you can do is minimize the boilerplate you need to wrap the exception-throwing code in.

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

If you are on Java 8, you can use this:

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

@FunctionalInterface public interface RunnableExc { void run() throws Exception; }

然后,暗示静态导入,您的代码将成为

Then, and implying static imports, your code becomes

ignoringExc(() -> test.setSomething1(0));
ignoringExc(() -> test.setSomething2(0));

这篇关于如何忽略Java中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆