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 anIOException
is thrown when accessing the underlyingBufferedReader
, it is wrapped in anUncheckedIOException
which will be thrown from theStream
method that caused the read to take place. This method will return a Stream if invoked on aBufferedReader
that is closed. Any operation on that stream that requires reading from theBufferedReader
after it is closed, will cause anUncheckedIOException
to 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 anUncheckedIOException
that will be thrown from theStream
method that caused the read to take place. In case anIOException
is 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節には記述されない。