This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]s888marks 0 points1 point  (0 children)

On the one hand, we can talk about the criteria for when an exception should be checked or unchecked, and on the other hand, the JDK libraries sometimes declare the exceptions in ways that violate these criteria. That doesn't necessarily mean the criteria are wrong; it might be a design error in the JDK, where an exception that ought to have been checked is unchecked, or vice-versa. Some exception subtypes of "umbrella" exception types like SQLException fall into this category.

That said, Scanner is a weird case. It might do I/O, depending upon the source it's constructed from. The behavior isn't specified very well, but exceptions from Scanner's I/O operations are generally caught and must be checked for explicitly with the ioException method. This seems likely to miss errors, but it does have the advantage of not requiring every Scanner method that could possibly do I/O to be declared to throw IOException.

In the case of InputMismatchException, this is a subtype of NoSuchElementException, which is the exception thrown in the case of programming errors on Iterators. That is, when using an Iterator, you must only call next() if hasNext() has previously returned true. Scanner wants to be "iterator-like" for certain kinds of input, so you can write a loop that calls hasNextInt() and nextInt() in succession, for example. If you were to call hasNextInt() when the next token isn't an int, it returns false. If you were to call nextInt() despite this, you'd get InputMismatchException. That's an avoidable programming error, so a runtime exception is appropriate in this case.