Java Reference
In-Depth Information
throw new UncheckedIOException("read error", ioe);
}
};
} catch (IOException ioe) {
throw new UncheckedIOException("input stream error", ioe);
}
consumer.accept(new Object());
}
public static InputStream acquireInputStream() {
return new InputStream() {
@Override
public int read() throws IOException {
return 1;
}
@Override
public void close() throws IOException {
System.out.println("Closing!");
super.close();
}
};
}
}
/* RESULT
Closing!
Trying to read!
*/
All in all, the try-with-resources approach is not too bad, although it is already getting a bit noisy.
You have to be careful about which blocks are nested in which way, but that is very manageable. The bigger
problem is that if you have a return value from your function, then the return from the catch block has to
match the return from the try block. The natural reaction for many Java developers will be to return null
at this point, but that is just opening up the possibility of encountering a NullPointerException , since it
expects the consumer to handle the situation while making it easy for them to ignore the situation. There are
three better options depending on your circumstance: unchecked exceptions, an exception-handling caller,
or a Result object.
Handling Resources by Throwing an Unchecked Exception
A very popular and very common solution is to handle checked exceptions by converting them to unchecked
exceptions and rethrowing them. This passes the responsibility for addressing the situation back to the
caller, and the exception will probably traverse quite a ways back up through the execution stack before it
encounters an exception handler. Hopefully, wherever that is will be well-suited for handling the exceptional
circumstance in an intelligent way.
 
Search WWH ::




Custom Search