Java Program to Handle Exceptions while reading User Input from Console

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at a Java Program to handle exceptions while reading user input from the console.

Exceptions are unexpected events that occur during the execution of a program. An exception might result due to an unavailable resource, unexpected input from a user, or simply a logical error on the part of the programmer.

The Scanner class will throw below three exceptions:

  • An IllegalStateException, if the scanner has been closed
  • A NoSuchElementException, if the scanner is active, but there is currently no token available for input
  • An InputMismatchException, if the next available token does not represent an integer

These exceptions are handled using “try-catch” blocks.

Let’s look at the Java program:

Output when given “-1” in the first input line itself:

 

Output when “-1” is not given in the first input line. hasNext() keeps looking for next input, until -1 is found. So we need to enter the second set of inputs with “-1” in it. 

Happy Learning :).

Please leave a reply in case of any queries.

Leave a Reply

Your email address will not be published. Required fields are marked *