EMZETT.
Login

try/catch/finally

In short: The try block holds code that may fail. If an exception occurs, the program jumps to the matching catch block. The finally block always runs, whether or not an error occurred.

In more detail: A try needs at least one catch or a finally. Several catch blocks catch different exception types, the first matching one wins. That is why the more specific type comes before the more general one.

In detail

try {
    int number = Integer.parseInt(input);
    System.out.println(100 / number);
} catch (NumberFormatException e) {
    System.out.println("Not a number");
} catch (ArithmeticException e) {
    System.out.println("Division by zero");
} finally {
    System.out.println("Cleanup");
}
  • finally: for clean-up (close file, drop connection). It also runs when the try contains a return.
  • Several types: in Java catch (A | B e), in Python except (A, B).
  • Python: try, except, else (when no error), finally.
  • JavaScript: try { } catch (e) { } finally { }, the error object has message and stack.
  • Pitfall: an overly broad catch (Exception e) hides programming errors.

See also: Exception handling, throw and throws