Try Catch And Finally
A try block surrounds code that may fail. A matching catch handles one exception type, and finally runs after either success or failure.
Catch only failures you can handle usefully. Here, an invalid array position has a clear recovery message.
Handle one expected failure
public class Main {
public static void main(String[] args) {
String[] zones = {"North", "South"};
int position = 3;
try {
System.out.println(zones[position]);
} catch (ArrayIndexOutOfBoundsException error) {
System.out.println("Unknown zone");
} finally {
System.out.println("Lookup finished");
}
}
}
Output:
Unknown zone
Lookup finished
Position 3 lies outside the two-element array, so the catch block prints a useful message. The finally block still reports that the lookup finished.
Do not catch broad Exception merely to hide a failure. It can swallow unrelated defects and leave the program in an uncertain state.
Catch an invalid age, print a useful message, and keep the finally notice.