Home Tutorial Java Core Exception Handling

 
 

Exception Handling
Posted on: June 16, 2010 at 12:00 AM
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

Related Tags for Exception Handling:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.