typestar

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

  1. Integer.parseInt throws on bad input; the typed catch names it.
  2. finally runs on success and failure alike.
  3. The loop survives the bad element and keeps processing.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Errors & files, step 25 of 29 in Language basics.

← Previous Next →

Try & catch in other languages