Example. Parsing integers safely

[comp1110-91]

Consider the following program:

void main() { int x = Integer.parseInt(IO.readln("Enter the first number: ")); int y = Integer.parseInt(IO.readln("Enter the second number: ")); IO.println(x + " * " + y + " = " + (x * y)); }

The program asks the user for two numbers and then calculates their product. This calculation only makes sense if the user actually enters integers. If they do not, the program crashes:

Enter the first number: comp Exception in thread "main" java.lang.NumberFormatException: For input string: "comp" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:565) at java.base/java.lang.Integer.parseInt(Integer.java:662) at Product.main(Product.java:2)

The crash happens in the line that defines the variable x above, specifically when calling Integer.parseInt with a string that is not a number. The error message describes both the kind of exception (java.lang.NumberFormatException, in short NumberFormatException) and the place where it happened.

We can handle this error by wrapping the call to Integer.parseInt in a try-catch block. Because we do this twice, we factor this functionality out into a new function, like so:

int getNumber(String prompt) { while(true) { try { return Integer.parseInt(IO.readln(prompt)); } catch(NumberFormatException e) { IO.println("This is not a number"); } } } void main() { int x = getNumber("Enter the first number: "); int y = getNumber("Enter the second number: "); IO.println(x + " * " + y + " = " + (x * y)); }

Here, getNumber becomes a safer version of the combination of Integer.parseInt and IO.readln - it keeps asking the user again and again until they enter a string that parses without throwing an exception.

bars magnifying-glass caret-down plus minus arrow-right xmark