Exception Handling


 

Exception Handling

In this section, you will learn how to ignore invalid input using Exception Handling.

In this section, you will learn how to ignore invalid input using Exception Handling.

Exception Handling

You all are aware of Exceptions and the methods to handle the exceptions. In this section, you will learn how to ignore invalid input using Exception Handling. Through the given code, you will come to know the use of exception handling. For this, we have allowed the user  to enter a series of integers from the command line. It will continue until he/she should enter (-1). If user will enter any string or some other characters then they would get ignored.

Here is the code:

import java.util.*;

public class ExceptionHandling {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter Integer values: ");
		int num = 0;
		while (num != -1) {
			try {
				num = input.nextInt();
			} catch (Exception e) {
				input.skip("\\w+");
			}
		}
	}
}

Output:

Enter Integer values:
1
2
3
hello
5
6
7
8
9
world
-1

Ads