How to catch an exception if the the input is string instead of integer?
It's confusing me since they used Try
, Catch
, Finally
which looks new to me. Please enlighten me thanks.
import java.util.*;
public class ExceptionSample {
public static void main (String[]args){
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
System.out.print("Enter dividend: ");
dividend = s.nextInt();
System.out.print("Enter divisor: ");
divisor = s.nextInt();
try {
quotient = dividend/divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
}
}
}
It would go something like this:
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
while (true) {
System.out.print("Enter dividend: ");
try {
dividend = s.nextInt();
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Dividend Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
while (true) {
System.out.print("Enter divisor: ");
try {
divisor = s.nextInt();
if (divisor == 0) {
throw new java.util.InputMismatchException();
}
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Divisor Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
try {
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
s.close();
}
When the Scanner#nextInt() method is used and one or more alpha characters are supplied a InputMismatchException is thrown. We trap this exception and use it to our advantage for validating the numerical input.