JDK-8275348 : Charset.forName() taking fallback default value
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.nio.charsets
  • Priority: P4
  • Status: Closed
  • Resolution: Approved
  • Fix Versions: 18
  • Submitted: 2021-10-15
  • Updated: 2021-10-25
  • Resolved: 2021-10-25
Related Reports
CSR :  
Description
Summary
-------

Provide an overload method to `java.nio.charset.Charset#forName()` that takes `fallback` Charset object.

Problem
-------

The existing `forName()` method throws `UnsupportedCharsetException` or `IllegalCharsetNameException` when the named charset is not available. The call site always has to try-catch it to determine whether the desired charset is returned or not.

Solution
--------

Provide an overload method that takes fallback Charset. If the named charset is not available, the fallback charset is returned.

Specification
-------------
Add a new method in `java.nio.charset.Charset` as follows:

    /**
     * Returns a charset object for the named charset. If the charset object
     * for the named charset is not available or {@code charsetName} is not a
     * legal charset name, then {@code fallback} is returned.
     *
     * @param  charsetName
     *         The name of the requested charset; may be either
     *         a canonical name or an alias
     *
     * @param  fallback
     *         fallback charset in case the charset object for the named
     *         charset is not available or {@code charsetName} is not a legal
     *         charset name. May be {@code null}
     *
     * @return  A charset object for the named charset, or {@code fallback}
     *          in case the charset object for the named charset is not
     *          available or {@code charsetName} is not a legal charset name
     *
     * @throws  IllegalArgumentException
     *          If the given {@code charsetName} is {@code null}
     *
     * @since 18
     */
    public static Charset forName(String charsetName,
                                  Charset fallback) 


Comments
Thanks, Joe. Allowing `null` is intentional so that the caller would know, if they want to, whether the Charset object for `charsetName` was returned or not, without the try-catch clause.
25-10-2021

Ah, okay; I see that case is already addressed in the @param tag. I think that design is fine; if you wanted an exception to be thrown in that case I think it would be fine too. Moving to Approved.
25-10-2021

No exception will be thrown merely if the fallback is null. Should it be added in @param section?
25-10-2021

Moving to Provisional, not Approved. What at the exceptional cases, if any, if the fallback is null?
25-10-2021