英文:
why I can't compile successfully with the following code?
问题
public class PoiSheetUtil{
public Workbook mergeExcelFiles(Workbook book, Map<Integer, InputStream> inMap) throws IOException,
InvalidFormatException{
inMap.forEach((k,v) -> {
Workbook b = WorkbookFactory.create(v);
//omit copy sheet method
copySheets(book.createSheet(), b.getSheetAt(k));
});
return book;
}
}
I get an error on line 5 which say that "Unhandled exception IOException, InvalidFormatException"
英文:
public class PoiSheetUtil{
public Workbook mergeExcelFiles(Workbook book, Map<Integer,InputStream> inMap) throws IOException,
InvalidFormatException{
inMap.forEach((k,v)->{
Workbook b = WorkbookFactory.create(v);
//omit copy sheet method
copySheets(book.createSheet(),b.getSheetAt(k));
});
return book;
}
}
I get an error on line 5 which say that "Unhandled exception IOException,InvalidFormatException"
答案1
得分: 2
问题在于上下文;潜在引发异常的代码位于 lambda 表达式中:
inMap.forEach((k,v) -> {
Workbook b = WorkbookFactory.create(v);
...
});
而在这种情况下,是 lambda 表达式未能正确处理异常。尝试使用以下方式:
inMap.forEach((k,v) -> {
try {
Workbook b = WorkbookFactory.create(v);
...
} catch (IOException | InvalidFormatException exc) {
throw new RuntimeException(exc);
}
});
或者使用其他类型的迭代结构(例如基于迭代器的 for
语句),它可以透明地传播异常:
for (var entry: inMap.entrySet()) {
final var k = entry.getKey();
final var v = entry.getValue();
...
}
英文:
The problem here is context; the code that potentially throws the exception sits in the lambda:
inMap.forEach((k,v)->{
Workbook b = WorkbookFactory.create(v);
...
});
and it's the lambda expression, that does not properly handle the exceptions in this case. Try
inMap.forEach((k,v)->{
try {
Workbook b = WorkbookFactory.create(v);
...
} catch (IOException | InvalidFormatException exc) {
throw new RuntimeException(exc);
}
});
or use some other kind of iteration construct (e.g., an iterator based for
statement) which can propagate the exception transparently:
for (var entry: inMap.entrySet()) {
final var k = entry.getKey();
final var v = entry.getValue();
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论