Exception handling · Topic 3 of 7
try, catch and finally
Definition​
Code that might fail goes in try. catch handles a specific problem, and finally always runs afterwards, whether or not an exception happened. Catch the most specific exception first.
Example code​
Parsing a number, with cleanup that always runs
class Demo {
static int parse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + text);
return -1;
} finally {
System.out.println("finished parsing " + text); // runs in both cases
}
}
public static void main(String[] args) {
System.out.println(parse("42"));
System.out.println(parse("abc"));
}
}
// Output:
// finished parsing 42
// 42
// Not a number: abc
// finished parsing abc
// -1
Finished this page? Track your progress (saved only in your browser).