6

ラムダ式内からチェック例外をキャッチする必要がある理由を説明してください。つまり、次のコードがコンパイルされないのはなぜですか...

public void doSomething(ObjectInputStream istream) throws IOException {
  // The read method throws an IOException.
  IntStream.range(0, 10).forEach(i -> someList.add(read(istream)));
}

しかし、これは?

public void doSomething(ObjectInputStream istream) throws IOException {
  IntStream.range(0, 10).forEach(i -> {
    try {
      // The read method throws an IOException.
      someList.add(read(istream));
    }
    catch (IOException ioe) {
      // Callee has to handle checked exception, not caller.
    }
  });
}

呼び出し先ではなく、スローされたチェック済み例外を処理する必要があるようです。

4

2 に答える 2