yohhoyの日記

技術的メモをしていきたい日記

java.io.UncheckedIOException例外クラス

Java 8で導入された java.io.UncheckedIOException 例外クラスについてメモ。

Stream処理における “Exception Tunneling” のために追加された例外。UncheckedIOException例外クラスは、従来からある検査例外java.io.IOExceptionをラップする目的で、RuntimeExceptionから派生した非検査例外(unchecked exception)である。

UncheckedIOExceptionが利用される具体例としてjava.io.BufferedReader#linesjava.nio.file.Files#linesメソッド等が挙げられる*1。いずれも戻り値型java.util.stream.Streamをもつメソッドとなっており、メソッドが返す “Streamオブジェクトに対する操作” 中にIOException例外が送出されたときUncheckedIOException例外にラップして再送出する動作仕様となっている。

public Stream<String> lines()
(snip)
If an IOException is thrown when accessing the underlying BufferedReader, it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place. This method will return a Stream if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.

http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--

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 an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException.
(snip)

http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-

関連URL

*1:UncheckedIOException は非検査例外のためメソッド宣言のthrows節には記述されない。