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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.clearurdoubt; import java.util.InputMismatchException; import java.util.Scanner; public class ExceptionHandler { public static void main(String[] args) { Scanner input = new Scanner(System.in); try { System.out.println("Please enter numbers separated by a space. (Enter -1 if Scanner needs to stop reading): "); int token = 0; while(input.hasNext()) // If -1 is not provided, Scanner blocks the execution to go further. { try { token = input.nextInt(); if(token == -1) // Stop reading the inputs { input.close(); break; } System.out.println( token + " "); } catch(InputMismatchException e) // if the input is not an integer, this exception is caught { System.out.println(input.next() + " is not a number."); } } } catch(IllegalStateException e) { // This exception is caught when the Scanner is alread closed // but we still call next() on the Scanner reference variable. System.out.println("Illegal State Exception raised. " + e.getMessage()); System.exit(-1); } catch(Exception e) { System.out.println("An exception raised. " + e.toString() + e.getMessage()); System.exit(-2); } System.out.println("Completed processing the input."); } } |
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.