Java 8で導入された java.io.UncheckedIOException 例外クラスについてメモ。
Stream処理における “Exception Tunneling” のために追加された例外。UncheckedIOException例外クラスは、従来からある検査例外java.io.IOExceptionをラップする目的で、RuntimeExceptionから派生した非検査例外(unchecked exception)である。
UncheckedIOExceptionが利用される具体例としてjava.io.BufferedReader#linesやjava.nio.file.Files#linesメソッド等が挙げられる*1。いずれも戻り値型java.util.stream.Streamをもつメソッドとなっており、メソッドが返す “Streamオブジェクトに対する操作” 中にIOException例外が送出されたときUncheckedIOException例外にラップして再送出する動作仕様となっている。
http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--
public Stream<String> lines()
(snip)
If anIOExceptionis thrown when accessing the underlyingBufferedReader, it is wrapped in anUncheckedIOExceptionwhich will be thrown from theStreammethod that caused the read to take place. This method will return a Stream if invoked on aBufferedReaderthat is closed. Any operation on that stream that requires reading from theBufferedReaderafter it is closed, will cause anUncheckedIOExceptionto be thrown.
http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-
public static Stream<String> lines(Path path, Charset cs) throws IOException
(snip)
After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in anUncheckedIOExceptionthat will be thrown from theStreammethod that caused the read to take place. In case anIOExceptionis thrown when closing the file, it is also wrapped as anUncheckedIOException.
(snip)
関連URL
- (PDF) Lambda Expressions in Java
- Everything about Java 8 - TechEmpower Blog
- Exception transparency in Java (Brian Goetz's Oracle Blog)
- http://mail.openjdk.java.net/pipermail/lambda-spec-experts/2012-September/000007.html
- java - What's idiom/best practice with UncheckedIOException and Stream API? - Stack Overflow
*1:UncheckedIOException は非検査例外のためメソッド宣言のthrows節には記述されない。