3

Would there ever be a case where an exception could be thrown by assigning the value of input.nextLine() to a String variable with the Scanner?

Like if you put

String foo = input.nextInt();

You would get an InputMismatchException. So what I'm wondering is if there's any possible way to get an exception from:

String foo = input.nextLine();

It might be a dumb question but I need to be absolutely sure.

Thanks in advance!

Justin
  • 164
  • 1
  • 14

1 Answers1

5

The answer in the docs:

Throws:
NoSuchElementException - if no line was found
IllegalStateException - if this scanner is closed

Tip for easier and safer life: Always refer to the docs.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • What would be a circumstance in which no line would be found? For example, when I run a program that asks the user for input, if I ONLY press return and nothing else, it doesn't crash. So if the user is being asked for input, what would he press in order for a line to not be found? – Justin Dec 02 '13 at 15:39
  • 1
    @Justin Assuming no other bugs, I think Ctrl + D will do the trick. – Dennis Meng Dec 02 '13 at 18:01
  • @DennisMeng: Thank you, that is the kind of thing I was looking for; learned something new! – Justin Dec 02 '13 at 22:25