Search code examples
javaconsole-applicationuser-inputjava.util.scannertype-safety

Type safety of input.nextLine?


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!


Solution

  • 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.