RFR: 8066869: Add Closeable::closeUnchecked that is the equivalent of close but throws UncheckedIOException
Stuart Marks
smarks at openjdk.org
Thu Jul 6 22:44:53 UTC 2023
On Thu, 6 Jul 2023 20:55:15 GMT, Brian Burkhalter <bpb at openjdk.org> wrote:
>> src/java.base/share/classes/java/io/Closeable.java line 60:
>>
>>> 58: * with it. If the stream is already closed then invoking this
>>> 59: * method has no effect.
>>> 60: *
>>
>> Can you add an example showing the recommended pattern of use?
>
>> Can you add an example showing the recommended pattern of use?
>
> One pattern is for example when reading from a stream and closing it is highly unlikely to generate an exception, then instead of the try block in
>
> InputStream in = ...;
> while(someCondition) {
> int b = in.read();
> // process b
> }
> try {
> in.close();
> } catch (IOException ignored) {
> }
>
> one could simply write
>
> in.closeUnchecked();
>
> and avoid the boilerplate imposed by the checked exception. This sort of code can be found in many places in the tests in `<OpenJDK>/test/jdk`.
OK, but note that using `closeUnchecked` in this way changes the behavior. Instead of ignoring an `IOException` it will get rethrown wrapped in an `UncheckedIOException`. This is probably reasonable for test code, where it's often acceptable to let exceptions propagate instead of handling them.
Are there other places in the JDK (in library code or in the tests) where `closeUnchecked` can and should be used? If so, maybe they should be updated as well.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/14789#discussion_r1254993519
More information about the core-libs-dev
mailing list