我有这段代码
List<JComponent> myList = new ArrayList<>();
fillmyList(myList); //Some method filling the list
try{
menuList.stream()
.filter(m->m.getClass().getMethod("setFont", new Class[]{Font.class}) != null) //unreported exception NoSuchMethodException; must be caught or declared to be thrown
.forEach(m -> m.setFont(someFont));
}
catch (NullPointerException | NoSuchMethodException e) {} //exception NoSuchMethodException is never thrown in body of corresponding try statement
但是,我有这个错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - exception java.lang.NoSuchMethodException is never thrown in body of corresponding try statement
如何解决这个问题?
答案 0 :(得分:3)
这不是例外,而是编译错误 你必须捕获可能抛出异常的lambda体,而不是整个流。
以下是在false
中为已抛出异常的流的元素返回filter()
的示例:
myList.stream()
.filter(m -> {
try {
return m.getClass()
.getMethod("setFont", new Class[] { Font.class }) != null;
} catch (NoSuchMethodException | SecurityException e) {
// log the exception
return false;
}
})
您当然可以使用不同的策略来抛出RuntimeException并停止处理。