Java methods and exception handling

Separate conversion errors from valid numeric values.

Java
class Main {
    static void showNumber(String text) {
        try {
            int value = Integer.parseInt(text);
            System.out.println(value * 2);
        } catch (NumberFormatException error) {
            System.out.println("Invalid integer");
        }
    }
    public static void main(String[] args) {
        showNumber("12");
        showNumber("abc");
    }
}
Output
24
Invalid integer

Explanation

Integer.parseInt converts decimal text within the int range. Invalid syntax or an out-of-range value throws NumberFormatException.

A try/catch handles the specific conversion failure so the program can continue. Validation rules such as an allowed age range should be checked separately after parsing.

Explore the dry run
Guided walkthroughReady
1class Main {
2 static void showNumber(String text) {
3 try {
4 int value = Integer.parseInt(text);
5 System.out.println(value * 2);
6 } catch (NumberFormatException error) {
7 System.out.println("Invalid integer");
8 }
9 }
10 public static void main(String[] args) {
11 showNumber("12");
12 showNumber("abc");
13 }
14}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Pass valid numeric text.text = 12
—
Parse successfully.value = 12
—
Multiply and print.value = 12
24
Pass invalid syntax.text = abc
24
Parsing throws; control jumps to the handler.text = abc
24
Print a recoverable error message.text = abc
24
Invalid integer

Cost and common mistakes

O(n) parsing time for text length n, with bounded int storage.

  • Successful parsing does not prove the number meets application constraints.
  • Multiplying a large int can overflow; use Math.multiplyExact when overflow must be detected.

Try it yourself

Predict showNumber('-3').

Reveal answer and reasoning

It prints -6 because -3 is valid integer syntax.

Further reading