java 忽略异常,如何忽略Java中的异常

I have the following code:

TestClass test=new TestClass();

test.setSomething1(0); //could, but probably won't throw Exception

test.setSomething2(0); //could, but probably won't throw Exception

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

}

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.

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.

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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值