Java Reference
In-Depth Information
Java 8 introduced some support for this programming convention: the java.io.UncheckedIOException
class, which explicitly exists to wrap checked IOException instances in an unchecked wrapper. Since
IOExceptions are at the root of the most common exception classes, this class provides a means to convert
most common exceptions into the unchecked form. The best way to do this is to use the UncheckedIOExcept
ion(String,IOException) constructor, which allows you to also attach a message for human consumption
to the point of conversion; in general, the more information you can provide in the case of an exception, the
better off you will be. For an example of this usage, see Listing 7-2.
Listing 7-2. An UncheckedIOException Wrapping an IOException
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.function.*;
public class Listing2 {
public static InputStream createInputStream() throws IOException {
return new ByteArrayInputStream("foobar".getBytes());
}
public static void call(Consumer<Object> c) {
c.accept(new Object());
}
public static void main(String[] args) {
call(it -> {
try (InputStream in = createInputStream()) {
throw new IOException("And with a kiss, I die!");
} catch (IOException e) {
throw new UncheckedIOException(
"Error working with input stream", e);
}
}
);
}
}
/* RESULT
Exception in thread "main" java.io.UncheckedIOException: Error working with input stream
at Listing1.lambda$main$0(Listing1.java:22)
at Listing1$$Lambda$1/558638686.accept(Unknown Source)
at Listing1.call(Listing1.java:14)
at Listing1.main(Listing1.java:18)
Caused by: java.io.IOException: And with a kiss, I die!
at Listing1.lambda$main$0(Listing1.java:20)
... 4 more
*/
 
Search WWH ::




Custom Search