Exceptions

try, catch and finally, and checked versus unchecked exceptions.

Java
public class Main {
  public static void main(String[] args) {
    try {
      int[] a = new int[2];
      a[5] = 1;
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Bad index");
    } finally {
      System.out.println("Done");
    }
  }
}
Output
Bad index
Done

finally runs whether or not an exception happened, so it is the place for clean-up.

KindMeaning
Checked (IOException)The compiler makes you catch or declare it
Unchecked (NullPointerException)Usually a bug in the code; not forced

Closing resources

try-with-resources closes files and connections for you.

Java
try (BufferedReader r = new BufferedReader(new FileReader("notes.txt"))) {
  System.out.println(r.readLine());
} catch (IOException e) {
  System.out.println("Could not read the file");
}
โ† Inheritance and interfacesCollections โ†’