LearnFrenzy
Sign in Take a free test

Exception Handling · Lesson 30 of 42

Checked Exceptions, Custom Exceptions and try-with-resources

5 min read Updated Nov 7, 2026 Saurabh Samir

Catching exceptions is half the story. The other half is throwing them well: choosing between checked and unchecked exceptions, creating your own exception types that describe business errors, and closing resources safely. This is where interviewers separate beginners from developers who have written real Java.

In this lesson

  • Checked vs unchecked exceptions
  • throw vs throws
  • Custom exceptions and chaining
  • try-with-resources and best practices

Checked vs unchecked

CheckedUnchecked
ExtendsException (not RuntimeException)RuntimeException
Compilerforces you to catch or declare with throwsno requirement
Representsexpected problems outside your controlprogramming errors or invalid input
ExamplesIOException, SQLExceptionNullPointerException, IllegalArgumentException

throw and throws

  • throw (a statement) actually throws an exception object: throw new IllegalArgumentException("…");
  • throws (in a method signature) declares that a method may throw a checked exception, passing responsibility to the caller.
import java.io.IOException;

public class Main {
    static String loadConfig(String name) throws IOException {     // declares a checked exception
        if (!name.endsWith(".properties")) {
            throw new IOException("Unsupported config file: " + name);   // throws it
        }
        return "loaded " + name;
    }

    static void setAge(int age) {
        if (age < 0) throw new IllegalArgumentException("age must be ≥ 0, got " + age);  // unchecked
    }

    public static void main(String[] args) {
        try {
            System.out.println(loadConfig("app.properties"));
            System.out.println(loadConfig("app.yaml"));
        } catch (IOException e) {
            System.out.println("Config error: " + e.getMessage());
        }
        try {
            setAge(-3);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

loaded app.properties
Config error: Unsupported config file: app.yaml
age must be ≥ 0, got -3

Common mistake: "unreported exception … must be caught or declared to be thrown"

Calling a method that throws a checked exception without a try/catch or a throws clause doesn't compile. Decide who can handle it sensibly: catch it where you can recover or show a message; otherwise declare it and let the caller decide.

Custom exceptions

Business rules deserve their own exception types. Callers can then catch exactly the error they care about, and the name documents what went wrong.

public class Main {
    public static void main(String[] args) {
        Wallet w = new Wallet(500);
        try {
            w.pay(200);
            w.pay(900);
        } catch (InsufficientBalanceException e) {
            System.out.println(e.getMessage() + " | short by ₹" + e.getShortfall());
        }
        System.out.println("Balance: ₹" + w.balance());
    }
}

class InsufficientBalanceException extends RuntimeException {
    private final double shortfall;

    InsufficientBalanceException(double needed, double available) {
        super("Payment of ₹" + needed + " declined");
        this.shortfall = needed - available;
    }

    double getShortfall() { return shortfall; }
}

class Wallet {
    private double balance;
    Wallet(double balance) { this.balance = balance; }

    void pay(double amount) {
        if (amount > balance) throw new InsufficientBalanceException(amount, balance);
        balance -= amount;
    }

    double balance() { return balance; }
}

Output

Payment of ₹900.0 declined | short by ₹600.0
Balance: ₹300.0

Checked or unchecked for custom exceptions?

Most modern Java code (including Spring) favours unchecked exceptions for business errors, because checked exceptions force throws clauses through many layers. Use a checked exception only when the caller is genuinely expected to recover, such as retrying a file or network operation.

Chaining: keep the original cause

When you translate a low-level exception into a meaningful one, pass the original as the cause so its stack trace isn't lost:

public class Main {
    public static void main(String[] args) {
        try {
            readOrderTotal("12a");
        } catch (OrderException e) {
            System.out.println(e.getMessage());
            System.out.println("caused by: " + e.getCause().getClass().getSimpleName());
        }
    }

    static int readOrderTotal(String raw) {
        try {
            return Integer.parseInt(raw);
        } catch (NumberFormatException e) {
            throw new OrderException("Order total is corrupt: '" + raw + "'", e);   // chain
        }
    }
}

class OrderException extends RuntimeException {
    OrderException(String message, Throwable cause) { super(message, cause); }
}

Output

Order total is corrupt: '12a'
caused by: NumberFormatException

try-with-resources

Files, database connections and network sockets must be closed even when something fails. Any object that implements AutoCloseable can be declared in the try (...) header and is closed automatically, in reverse order:

public class Main {
    public static void main(String[] args) {
        try (Resource db = new Resource("database");
             Resource file = new Resource("report.csv")) {
            System.out.println("working with both");
            throw new IllegalStateException("something failed");
        } catch (IllegalStateException e) {
            System.out.println("handled: " + e.getMessage());
        }
    }
}

class Resource implements AutoCloseable {
    private final String name;
    Resource(String name) { this.name = name; System.out.println("open " + name); }
    @Override public void close() { System.out.println("close " + name); }
}

Output

open database
open report.csv
working with both
close report.csv
close database
handled: something failed

Before Java 7 this needed a finally block with nested null checks and its own try/catch. Today, always use try-with-resources for anything that needs closing.

Best practices

  • Never swallow exceptions: an empty catch (Exception e) {} hides bugs. At least log them.
  • Catch specific types you can handle; let the rest propagate.
  • Throw early, catch late: validate inputs at the start of a method; handle errors at a level that can show a message or retry.
  • Write useful messages with the bad value: "age must be ≥ 0, got -3".
  • Don't use exceptions for normal control flow – they are slow and confusing for that.

Practice

Try it yourself

  1. Create an InvalidEmailException and throw it from validate(email) when there is no "@".

    Show solution
    public class Main {
        static String validate(String email) {
            if (email == null || !email.contains("@")) throw new InvalidEmailException(email);
            return email.toLowerCase();
        }
    
        public static void main(String[] args) {
            try {
                System.out.println(validate("Asha@Mail.com"));
                validate("asha.mail.com");
            } catch (InvalidEmailException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    class InvalidEmailException extends RuntimeException {
        InvalidEmailException(String email) { super("Invalid email: " + email); }
    }

    Output

    asha@mail.com
    Invalid email: asha.mail.com

Quick check

What is the difference between throw and throws?

throw throws an exception object; throws in a method signature declares checked exceptions the method may throw.

Is IOException checked or unchecked?

Checked – it must be caught or declared.

What must a class implement to be used in try-with-resources?

AutoCloseable (or its sub-interface Closeable).

Summary

  • Checked exceptions must be handled or declared; unchecked ones signal bugs and bad input.
  • Create custom exceptions for business errors and chain the original cause.
  • Close resources with try-with-resources; never swallow exceptions.

Interview practice: Java strings, exceptions and generics.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links