-1
System.out.println("Enter floor: ");
int f=x.nextInt();
p.setFloor(f);

This code is associated with an object

public void setFloor(int floor){
    try{
        this.floor = floor ;
    }catch (InputMismatchException e){
        System.out.println("Enter only digits");
    }
}

Output

Enter floor:
hesdd
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)

Why is the catch not working?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
DCodes
  • 789
  • 1
  • 11
  • 27
  • 1
    `int f=x.nextInt();` should be in the `try/catch` block – ernest_k May 07 '18 at 16:41
  • you want to try this `int f=x.nextInt();` don't you – Pavneet_Singh May 07 '18 at 16:42
  • Why would you expect `this.floor = floor` to throw an `InputMismatchException`? It's the `nextInt()` method that can throw the exception, but you shouldn't need to catch that. Instead, call `hasNextInt()` before trying to call `nextInt()` – Andreas May 07 '18 at 16:42

1 Answers1

4

InputMismatchException was thrown when calling Scanner.nextInt, you shoud catch it immediatly:

int f;
try {
   f = x.nextInt();
}catch (InputMismatchException e){
    System.out.println("Enter only digits");
}
xingbin
  • 27,410
  • 9
  • 53
  • 103