Search code examples
java.util.scannerjavasystem.in

Calling next() on a Scanner initialized by a closed stream doesn't throw IllegalStateException


The Scanner documentation says that when one calls next() on a closed stream then these two exceptions may be thrown:

NoSuchElementException - if no more tokens are available

IllegalStateException - if this scanner is closed

Furthermore hasNext() may throw this exception:

IllegalStateException - if this scanner is closed

Now let's assume that we have this code:

FileInputStream fis = new FileInputStream(new File("somefile"));
Scanner sc = new Scanner(fis);
// sc.close();
// sc = new Scanner(fis);
// somefile contents: word1 word2 word3
System.out.println(sc.next());

This will print word1 as expected. If we uncomment sc.close(); sc = new Scanner(fis); a NoSuchElementException will be thrown when sc.next() will be executed.

This behaviour seems strange to me. Shouldn't hasNext() and next() throw an IllegalStateException as the InputStream is closed? Please, explain why this is happening.


Solution

  • It seems you have misinterpreted Scanner’s documentation. It says next() will throw a NoSuchElementException if no more tokens are available; this is the case when the underlying stream is either at its end or has been closed. It will only throw an IllegalStateException if the scanner itself was closed—which does not happen in your question.