为什么我无法成功编译以下代码?

huangapple go评论81阅读模式
英文:

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&lt;Integer,InputStream&gt; inMap) throws IOException, 
    InvalidFormatException{
        inMap.forEach((k,v)-&gt;{
            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)-&gt;{
    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)-&gt;{
    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();
     ...
}

huangapple
  • 本文由 发表于 2020年10月24日 16:41:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64511531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定