0

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.

Community
  • 1
  • 1
Master_ex
  • 779
  • 7
  • 12
  • As @Andreas said, in my case it threw IllegalStateException: Scanner closed. – wawek Sep 03 '15 at 06:26
  • 1
    I'm not sure what you're saying. `sc.hasNext()` does through a scanner closed exception in that code, it doesn't return false. – Zarwan Sep 03 '15 at 06:26
  • You are right, I got confused. I will update my question a bit later. – Master_ex Sep 03 '15 at 06:36
  • I can't edit my comment anymore and I am truly embarrassed that I screwed this up, but *throw – Zarwan Sep 03 '15 at 06:38
  • OK, I have totaly misunderstood the conditions of my problem. So, I have updated the question which is as it seems very different from the original. Thank you for your time :-) – Master_ex Sep 03 '15 at 07:02

1 Answers1

1

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.

Bombe
  • 74,913
  • 20
  • 118
  • 125