简体   繁体   中英

Why Scanner constructors with String encoding argument throw no UnsupportedEncodingException?

Constructors of almost all classes from java.io and Formatter always throw checked UnsupportedEncodingException if String encoding is a constructor's argument.

But Scanner is totally different - it throws only runtine IllegalArgumentException if encoding argument is misspelled/wrong.

Scanner class constructor seems to be the only one not to throw checked UnsupportedEncodingException in all java API (having String encoding a constructor's argument), throwing only runtime IllegalArgumentException.

Why is that? Just a design/compatibility quirk or some deep reasoning behind that?

First of all, the only people who can answer this definitively are the people who designed the respective interfaces.

I think the decision was made deliberately.

The UnsupportedEncodingException exception is a bit of an anomaly:

  • It is a subtype of IOException where encoding / decoding is actually orthogonal to I/O: consider the String(byte[], String) constructor.

  • It is a checked exception, but there are convincing arguments that it should be unchecked:

    1. If UnsupportedEncodingException is actually thrown it is most likely the result of a programming error rather than a error that your application might be able to recover from.

    2. One of the most common use-cases is to give the string "UTF-8" as the encoding name. The Java specifications guarantee that UTF-8 will always be supported by a compliant JVM, yet since the exception is checked, we still need to write a handler ... for a failure that cannot happen.

Given that these issues, I think the designers decided that it was better not to use UnsupportedEncodingException in Scanner , and to use an unchecked exception for the case where the requested encoding is not supported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM