java中为什么流要 异常,为什么我们不能在Java 8流中抛出异常?

E.g:

Person result = persons.stream()

.filter(x -> {

if ("test".equals(x.getName() ) ) {

throw new IOException("not possible inside stream y ?"); //any checked exception

}

//code here

})

M looking for reason why it is not being allowed ? Even if method in which code is declared throws IOException

解决方案

your code is working perfectly, apart from a missing semi colon at the end of the throw new ... line, and from a missing a return statement that may be hidden in // code here.

What you can't do is throw a checked exception (which RuntimeException is not) because checked exception are part of the method signature and the Predicate.test method do not declare one.

EDIT :

To see more precisely what is happening and why you can't throw a checked exception here, here is how you could have written the code without lambda :

From this :

public Person myMethod() throws IOException {

Person result = persons.stream()

.filter(x -> {

if ("test".equals(x.getName() ) ) {

throw new IOException("not possible inside stream y ?"); //any checked exception

}

//code here

return true;

});

return person;

}

to this :

public Person myMethod() throws IOException {

Person result = persons.stream()

.filter(new Predicate() {

public boolean test(Person x) {

if ("test".equals(x.getName() ) ) {

throw new IOException("not possible inside stream y ?"); //any checked exception

}

//code here

return true;

}

});

return person;

}

As you can see, the code inside the lambda expression is now inside the test method of an anonymous Predicate class, which is not declaring any checked exception.

Why Predicate ? Because it is what the filter method is expecting, and you can use a lambda instead of a conventional object because it is a single method interface : only test is abstract, and your lambda signature should be the same as the Predicate.test method.

If you really wish to be able to handle checked exceptions, the linked post (in a comment from Frederico) show some ways to bypass these limitations.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值