Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Difference between InputMismatchException and NoSuchElementException

843923Mar 1 2011 — edited Mar 2 2011
Hi all,

I just have a code like this, and well I was trying some things and saw that InputMismatchException and NoSuchElementException work in the same way ... so what is the difference? the api says that NoSuchElementException is used when the "input is exhausted" but I do not understand what it means.

Here are the codes I was using.
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);		
		
		try{
			int a = in.nextInt();
			System.out.println("The value of a is:" + a);
		}
		catch(InputMismatchException e){
			System.err.println("Only numbers");
			in.nextLine();
		}
	}
}
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);		
		
		try{
			int a = in.nextInt();
			System.out.println("The value of a is:" + a);
		}
		catch(NoSuchElementException e){
			System.err.println("Only numbers");
			in.nextLine();
		}
	}
}
Thanks,
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 30 2011
Added on Mar 1 2011
2 comments
831 views