Skip to content

Chapter 16 of 37

Exception Handling

Handle checked and unchecked failures with try, catch, throw, finally, and resources.

38 minutes 10 quick checksBy Subha Prasad
Lesson 16 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Checked exceptions must be caught or declared with throws; runtime exceptions and errors are unchecked. Throw specific meaningful exceptions and catch the most specific types before general ones.

Safe boundaries

static int parsePositive(String text) {
    try {
        int value = Integer.parseInt(text);
        if (value <= 0) throw new IllegalArgumentException("positive required");
        return value;
    } catch (NumberFormatException error) {
        throw new IllegalArgumentException("invalid integer", error);
    } finally {
        // unconditional follow-up; not usually resource closing
    }
}

Preserve the cause when translating exceptions. Avoid empty catches and broad catch (Exception) except at an application boundary. finally normally runs even after return, but try-with-resources is safer for closing. Multiple resources close in reverse order and suppressed exceptions remain inspectable. Use exceptions for exceptional failure, not ordinary optional outcomes; validate early and document checked failure contracts.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes checked exception?
Which Java term matches this description: A non-runtime exception that must be caught or declared.
Which statement best describes unchecked exception?
Which Java term matches this description: A RuntimeException or Error not subject to catch-or-declare.
Which statement best describes finally?
Which Java term matches this description: A block normally run after try/catch for unconditional follow-up.
Which statement best describes throw?
Which Java term matches this description: A statement that raises a specific Throwable object.
Which statement best describes throws?
Which Java term matches this description: A method-clause declaring checked exceptions that may escape.

0 of 10 checks passed

Your progress is saved on this device.