InfoparkDailyCAREER TOOLS

Java · Lesson 9 of 9

Exceptions

try / catch / finally, checked vs unchecked exceptions and try-with-resources.

An exception signals that something went wrong at run time. Unhandled, it stops the program with a stack trace.

  • try { … } catch (Type e) { … } finally { … } — handle errors; finally always runs.
  • Checked exceptions (e.g. IOException) must be caught or declared with throws.
  • Unchecked exceptions (RuntimeException subclasses such as NullPointerException, IllegalArgumentException) usually indicate bugs.
  • throw new IllegalArgumentException("…") raises your own.
  • try-with-resources closes files and connections automatically: try (var reader = …) { }.

Example program

Run with JDK 17+: java Main.java
public class Main {
    static int parseExperience(String text) {
        int years = Integer.parseInt(text);           // may throw NumberFormatException
        if (years < 0) {
            throw new IllegalArgumentException("Experience can't be negative");
        }
        return years;
    }

    public static void main(String[] args) {
        String[] inputs = {"3", "three", "-1"};
        for (String input : inputs) {
            try {
                System.out.println("Parsed: " + parseExperience(input));
            } catch (NumberFormatException e) {
                System.out.println("Not a number: " + input);
            } catch (IllegalArgumentException e) {
                System.out.println("Invalid: " + e.getMessage());
            } finally {
                System.out.println("-- checked " + input);
            }
        }
    }
}

Output

Parsed: 3
-- checked 3
Not a number: three
-- checked three
Invalid: Experience can't be negative
-- checked -1

Save the code as Main.java and run java Main.java (JDK 11+ runs single files directly). Names and figures are fictional.

Key points

  • Catch specific exceptions, most specific first.
  • Checked exceptions must be handled or declared.
  • Use try-with-resources for anything that needs closing.

Quick check

Which block always runs, whether or not an exception occurs?

Practice task

Write safeDivide(int a, int b) that catches ArithmeticException for b = 0 and returns 0 with a message.

Interview corner

Checked vs unchecked exceptions?

Checked exceptions are verified by the compiler and must be caught or declared (IOException). Unchecked exceptions extend RuntimeException and are not enforced (NullPointerException).

throw vs throws?

throw raises an exception object inside a method. throws in a method signature declares which checked exceptions the method may pass to its caller.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.