Try & catch in Java
Catch the exception you expect; let the rest travel.
var inputs = new String[] { "10", "zero", "4" };
for (var text : inputs) {
try {
var n = Integer.parseInt(text);
System.out.println("100 / " + n + " = " + 100 / n);
} catch (NumberFormatException e) {
System.out.println("'" + text + "' is not a number");
} finally {
System.out.println("checked one input");
}
}
How it works
Integer.parseIntthrows on bad input; the typed catch names it.finallyruns on success and failure alike.- The loop survives the bad element and keeps processing.
Keywords and builtins used here
catchfinallyfornewtryvar
The run, in numbers
- Lines
- 12
- Characters to type
- 312
- Tokens
- 102
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 64 seconds.
Step 1 of 3 in Errors & files, step 25 of 29 in Language basics.