exceptions

try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    // handle it
} finally {
    System.out.println("always printed");
}

Checked versus unchecked

Checked exceptions must be declared or caught Unchecked exceptions can propagate without declaration

The compiler enforces the first The second is the normal case for programming errors

Catch order

Catch the most specific type first A broad catch above a specific one makes the specific branch unreachable

finally

finally runs on both success and failure Use it for cleanup that must happen Try-with-resources is the modern form for closeable objects

try (var in = new Scanner(System.in)) {
    in.nextLine();
}

The resource closes automatically That removes the finally boilerplate entirely

What not to do

Do not catch Exception and print a message Do not use exceptions for normal control flow Do not swallow an exception and pretend the operation succeeded

Next

Streams in 08 streams

Posted