0
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"

jiangke
  • 305
  • 3
  • 13
  • 1
    IOException and InvalidFormatException are checked exceptions so you need to catch them and handle them somewhere(for example you can catch them in the the method that calls your method mergeExcelFiles() ) – VFX Oct 24 '20 at 08:48

1 Answers1

2

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();
     ...
}
Dirk
  • 30,623
  • 8
  • 82
  • 102