Skip to content

Conversation

@garydgregory
Copy link
Member

Add and use IOUtils.closeQuietly(Closeable, Throwable)

  • Read the contribution guidelines for this project.
  • Read the ASF Generative Tooling Guidance if you use Artificial Intelligence (AI).
  • I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute?
  • Run a successful build using the default Maven goal with mvn; that's mvn on the command line by itself.
  • Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.

@garydgregory garydgregory merged commit 68be2fb into apache:master Dec 11, 2025
27 of 39 checks passed
@garydgregory garydgregory deleted the feature/IOUtils.closeQuietly(Closeable,_Throwable) branch December 11, 2025 21:21
@ppkarwasz
Copy link
Contributor

Nice PR! 💯

I honestly believe this useful method was missing since Java 7 introduced addSuppressed.

* @since 2.22.0
* @see Throwable#addSuppressed(Throwable)
*/
public static <T extends Throwable> T closeQuietly(final Closeable closeable, final T throwable) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This signature causes the following call to become ambiguous:

closeQuietly(closeable, e::addSuppressed);

Maybe we might consider inverting the order of the arguments?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no type casting needed in the call sites in:

  • org.apache.commons.io.FileUtils.lineIterator(File, String)
  • org.apache.commons.io.LineIterator.hasNext()
  • org.apache.commons.io.output.FileWriterWithEncoding.initWriter(File, Object, boolean)
  • org.apache.commons.io.IOUtilsTest.testCloseQuietly_CloseableIOExceptionAddSuppressed()

I would only see a typecast needed for a null literal argument, and making the method weird compared to the others for this one use case doesn't seem worth it to me.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly I don't understand why the compiler gets confused about e::addSuppressed (which is clearly not a Throwable), but experimentally it does.
Any idea why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants