Share on Google+Share on Google+

Exception Handling

Advertisement
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

Advertisements

Posted on: June 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.