Java methods and exception handling
Separate conversion errors from valid numeric values.
On this page
Methods, strings, and return values.
- Separate conversion errors from valid numeric values.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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");
}
}24 Invalid integer
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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"); }}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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
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.