← Chapter 8 — Exceptions & Collections

30. Exception Handling

mixed

Description

Exceptions represent problems that interrupt normal program flow. Java uses try, catch, finally, and throws to make error handling explicit.

Handle an exception where you can add useful recovery or context. Do not silently ignore a problem; tell the user, log it, or let it reach a layer that can respond.

Subtopics

try and catch

Description

Put risky code in try and recovery in catch.

Explanation

Catch the most specific exception type you can handle.

Example

try { Integer.parseInt("x"); } catch (NumberFormatException e) { }

finally and throws

Description

finally runs after try/catch; throws declares a possible exception.

Explanation

Try-with-resources is preferred for closable resources.

Example

void read() throws java.io.IOException { }

Explanation

Checked exceptions must be handled or declared, while unchecked RuntimeException subclasses usually reveal programming or data-validation mistakes. Learn the cause before choosing a response.

Example

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int score = Integer.parseInt("ninety");
            System.out.println(score);
        } catch (NumberFormatException e) {
            System.out.println("Please enter a numeric score.");
        }
    }
}

Key points

  • try encloses risky code.
  • catch handles a matching exception.
  • Do not swallow exceptions silently.

Video

Open video

Open reference