Reading history

Java Exception Handling: try, catch, finally, throw, throws

4 min read 0 views

Learn Java exception handling: try, catch and finally, checked vs unchecked exceptions, throw and throws, custom exceptions and try-with-resources.

An exception is an event that interrupts the normal flow of a program: text that is not a number, division by zero, a missing file. If nothing catches it, the program stops with a stack trace. Java’s try, catch and finally let you handle problems gracefully, and throw and throws let your own code report errors. Java also splits exceptions into checked and unchecked, which this lesson explains.

In this lesson you will learn

  • How try, catch and finally work
  • Catching different exception types separately
  • Checked vs unchecked exceptions
  • Throwing exceptions and declaring them with throws
  • Writing your own exception class

try, catch and finally

public class Main {
    public static void main(String[] args) {
        String[] inputs = {"42", "abc", "0"};
        for (String in : inputs) {
            try {
                int n = Integer.parseInt(in);
                System.out.println("100 / " + n + " = " + (100 / n));
            } catch (NumberFormatException e) {
                System.out.println("Not a number: " + in);
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            } finally {
                System.out.println("-- checked " + in);
            }
        }
    }
}

Output

100 / 42 = 2
-- checked 42
Not a number: abc
-- checked abc
Cannot divide by zero
-- checked 0
  • Code that might fail goes in the try block. When an exception occurs, Java jumps straight to the first catch whose type matches.
  • Integer.parseInt("abc") throws NumberFormatException; integer division by zero throws ArithmeticException.
  • finally runs every time, with or without an exception. It is the place for clean-up such as closing a file.

throw, throws and Custom Exceptions

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) { super(message); }
}

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

    void withdraw(double amount) throws InsufficientFundsException {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount > balance) throw new InsufficientFundsException("need " + (amount - balance) + " more");
        balance -= amount;
    }

    double getBalance() { return balance; }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account(500);
        double[] requests = {200, -5, 900};
        for (double r : requests) {
            try {
                acc.withdraw(r);
                System.out.println("Withdrew " + r + ", balance " + acc.getBalance());
            } catch (InsufficientFundsException e) {
                System.out.println("Checked exception: " + e.getMessage());
            } catch (IllegalArgumentException e) {
                System.out.println("Unchecked exception: " + e.getMessage());
            }
        }
    }
}

Output

Withdrew 200.0, balance 300.0
Unchecked exception: amount must be positive
Checked exception: need 600.0 more
  • throw new ... raises an exception from your own code.
  • InsufficientFundsException extends Exception, so it is a checked exception. The method must declare it with throws, and callers must catch it or declare it too; otherwise the code does not compile.
  • IllegalArgumentException extends RuntimeException, so it is unchecked: the compiler does not force anyone to handle it.
  • getMessage() returns the text passed to the constructor.

Checked vs Unchecked

CheckedUnchecked
ExtendsExceptionRuntimeException
Compiler forces handling?YesNo
Typical causeOutside problems: missing file, network downBugs: null reference, bad index, bad argument
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException

Serious problems such as OutOfMemoryError extend Error and are not meant to be caught.

try-with-resources

Objects that must be closed (files, database connections) can be opened in the try brackets. Java closes them automatically, even after an exception:

try (var reader = new java.io.BufferedReader(new java.io.FileReader("data.txt"))) {
    System.out.println(reader.readLine());
} catch (java.io.IOException e) {
    System.out.println("Could not read file: " + e.getMessage());
}

Common Mistakes

  1. Catching Exception everywhere. It hides real bugs; catch the specific types you expect.
  2. An empty catch block. At least log the problem.
  3. Catching a parent type before a child type, such as Exception before IOException. The compiler rejects the unreachable catch.
  4. Using exceptions for normal control flow instead of a simple if check.

Practice Exercises

Exercise 1. Write safeParse(String s) that returns the number, or -1 if s is not a valid integer.

Show answer
static int safeParse(String s) {
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return -1;
    }
}

Exercise 2. Catch two exception types in one block.

Show answer
try {
    // risky code
} catch (NumberFormatException | ArithmeticException e) {
    System.out.println("Bad input: " + e.getMessage());
}

Frequently Asked Questions

What is the difference between throw and throws?

throw actually raises an exception inside a method. throws in a method’s signature warns callers which checked exceptions it may raise.

Does finally run if the try block returns?

Yes. finally runs before the method returns. It is skipped only in extreme cases such as System.exit().

Summary

  • try holds risky code, catch handles specific types, and finally always runs.
  • Checked exceptions must be caught or declared; unchecked ones need not be.
  • throw raises; throws declares.
  • Use try-with-resources for files and connections.

Next: Java Interfaces and Abstract Classes.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *