LearnFrenzy
Sign in Take a free test

Java Programming · Topic 17 of 28

Exception Handling

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Exception Handling · Study material

An exception is an event that disrupts the normal flow of a program: dividing by zero, reading past the end of an array, parsing "abc" as a number, a missing file or a network timeout. Exception handling lets a program detect such problems, respond to them – retry, use a default, show a message, roll back – and keep running instead of crashing. Java's model is built on the Throwable class hierarchy and five keywords: try, catch, finally, throw and throws, plus try-with-resources for closing files and connections automatically. Java is unusual in having checked exceptions, which the compiler forces you to handle or declare. This page explains the hierarchy, checked vs unchecked exceptions, catch order and multi-catch, custom exceptions, chaining, try-with-resources, the tricky interaction of finally and return, and assertions – all with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • The exception hierarchy; checked vs unchecked
  • try, catch and finally
  • Multi-catch and the order of catch blocks
  • throw, throws and custom exceptions
  • Chaining, try-with-resources and suppressed exceptions
  • finally and return; assertions; best practices

The exception hierarchy

ClassMeaningExamplesChecked?
Throwableroot of everything that can be thrown––
Errorserious JVM problems – do not catchOutOfMemoryError, StackOverflowError, AssertionErrorunchecked
Exceptionconditions a program may want to handleIOException, SQLException, InterruptedExceptionchecked
RuntimeExceptionusually programming errorsNullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundsExceptionunchecked

try, catch and finally

Code that may fail goes in try. If an exception is thrown, Java skips the rest of the try block and runs the first catch whose type matches. finally runs in every case – after normal completion, after a caught exception and even when an exception propagates or a return occurs – which makes it the place for clean-up.

public class Main {
    static int divide(int a, int b) {
        return a / b;                                   // throws ArithmeticException when b == 0
    }

    public static void main(String[] args) {
        int[] divisors = {5, 0, 2};
        for (int d : divisors) {
            try {
                System.out.println("100 / " + d + " = " + divide(100, d));
            } catch (ArithmeticException e) {           // handle the problem and carry on
                System.out.println("cannot divide by zero: " + e.getMessage());
            } finally {                                 // runs whether or not an exception happened
                System.out.println("  (checked " + d + ")");
            }
        }
        System.out.println("program continues normally");
    }
}

Output

100 / 5 = 20
  (checked 5)
cannot divide by zero: / by zero
  (checked 0)
100 / 2 = 50
  (checked 2)
program continues normally

Checked vs unchecked exceptions

A checked exception (a subclass of Exception but not of RuntimeException) must be either caught or declared with throws in the method signature – the compiler enforces it. Unchecked exceptions (RuntimeException and Error) need not be declared. Use checked exceptions for recoverable conditions the caller must think about, and unchecked ones for bugs and invalid arguments.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    // CHECKED: the compiler forces callers to handle or declare it (throws)
    static String firstLine(String text) throws IOException {
        try (BufferedReader r = new BufferedReader(new StringReader(text))) {
            String line = r.readLine();
            if (line == null) throw new IOException("empty input");
            return line;
        }
    }

    // UNCHECKED (RuntimeException): usually a programming bug; handling is optional
    static int parseAge(String s) {
        int age = Integer.parseInt(s);                  // may throw NumberFormatException
        if (age < 0) throw new IllegalArgumentException("age cannot be negative: " + age);
        return age;
    }

    public static void main(String[] args) {
        try {
            System.out.println(firstLine("Java\nPython"));
            System.out.println(firstLine(""));
        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }

        for (String s : new String[]{"25", "-3", "abc"}) {
            try {
                System.out.println("age " + parseAge(s));
            } catch (NumberFormatException e) {         // more specific first
                System.out.println("not a number: " + s);
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

Output

Java
IOException: empty input
age 25
age cannot be negative: -3
not a number: abc

Multi-catch and catch order

Catch blocks are tried from top to bottom, so put more specific types first – a subclass after its superclass is unreachable and a compile error. One catch (A | B e) handles unrelated types the same way.

public class Main {
    static String risky(int choice) {
        Object[] data = {"text", 42};
        int[] arr = new int[3];
        switch (choice) {
            case 0 -> { return "value " + arr[5]; }                  // ArrayIndexOutOfBoundsException
            case 1 -> { return "length " + ((String) data[1]).length(); }   // ClassCastException
            case 2 -> { return "number " + Integer.parseInt("x1"); } // NumberFormatException
            case 3 -> { return "ratio " + (10 / (choice - 3)); }     // ArithmeticException
            default -> { return "all good"; }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 4; i++) {
            try {
                System.out.println(risky(i));
            } catch (ArrayIndexOutOfBoundsException | ClassCastException e) {   // multi-catch (Java 7+)
                System.out.println(i + ": bad data – " + e.getClass().getSimpleName());
            } catch (IllegalArgumentException e) {      // also catches NumberFormatException (a subclass)
                System.out.println(i + ": bad argument – " + e.getMessage());
            } catch (RuntimeException e) {              // most general LAST
                System.out.println(i + ": other – " + e);
            }
        }
    }
}

Output

0: bad data – ArrayIndexOutOfBoundsException
1: bad data – ClassCastException
2: bad argument – For input string: "x1"
3: other – java.lang.ArithmeticException: / by zero
all good

throw, throws and custom exceptions

throw raises an exception object; throws in a method header declares which checked exceptions may escape. Create your own exception classes by extending Exception (checked) or RuntimeException (unchecked), passing a clear message to super and adding useful fields.

class InsufficientFundsException extends Exception {          // checked custom exception
    private static final long serialVersionUID = 1L;
    private final double shortBy;
    InsufficientFundsException(double shortBy) {
        super("insufficient funds, short by Rs " + shortBy);
        this.shortBy = shortBy;
    }
    double shortBy() { return shortBy; }
}

class AccountFrozenException extends RuntimeException {      // unchecked custom exception
    private static final long serialVersionUID = 1L;
    AccountFrozenException(String id) { super("account " + id + " is frozen"); }
}

class Account {
    private final String id;
    private double balance;
    private boolean frozen;
    Account(String id, double balance) { this.id = id; this.balance = balance; }
    void freeze() { frozen = true; }

    void withdraw(double amt) throws InsufficientFundsException {
        if (frozen) throw new AccountFrozenException(id);
        if (amt > balance) throw new InsufficientFundsException(amt - balance);
        balance -= amt;
    }
    double balance() { return balance; }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account("SB-9", 1000);
        double[] requests = {300, 900, 200};
        for (double r : requests) {
            try {
                acc.withdraw(r);
                System.out.println("withdrew " + r + ", left " + acc.balance());
            } catch (InsufficientFundsException e) {
                System.out.println(e.getMessage() + " (need " + e.shortBy() + " more)");
            }
        }
        acc.freeze();
        try {
            acc.withdraw(10);
        } catch (InsufficientFundsException | AccountFrozenException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}

Output

withdrew 300.0, left 700.0
insufficient funds, short by Rs 200.0 (need 200.0 more)
withdrew 200.0, left 500.0
AccountFrozenException: account SB-9 is frozen

try-with-resources

Any object that implements AutoCloseable can be declared in the parentheses of try. It is closed automatically at the end of the block, in reverse order of opening, before any catch or finally runs – no more forgotten close() calls.

class Connection implements AutoCloseable {
    private final String name;
    Connection(String name) { this.name = name; System.out.println("open " + name); }
    void query(String sql) {
        if (sql.contains("DROP")) throw new IllegalStateException("dangerous query");
        System.out.println(name + " runs: " + sql);
    }
    @Override public void close() { System.out.println("close " + name); }
}

public class Main {
    public static void main(String[] args) {
        // Resources are closed automatically, in REVERSE order, even when an exception is thrown
        try (Connection db = new Connection("db"); Connection cache = new Connection("cache")) {
            db.query("SELECT 1");
            cache.query("DROP ALL");
            System.out.println("not reached");
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
        } finally {
            System.out.println("finally");
        }
    }
}

Output

open db
open cache
db runs: SELECT 1
close cache
close db
caught: dangerous query
finally

Exception chaining

When a low-level exception is translated into a higher-level one, pass the original as the cause so the full story stays in the stack trace.

class DataLoadException extends Exception {
    private static final long serialVersionUID = 1L;
    DataLoadException(String msg, Throwable cause) { super(msg, cause); }    // keep the original cause
}

public class Main {
    static int loadPrice(String raw) throws DataLoadException {
        try {
            return Integer.parseInt(raw.strip());
        } catch (NumberFormatException e) {
            throw new DataLoadException("bad price in feed: '" + raw + "'", e);   // translate, don't lose
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(loadPrice(" 499 "));
            System.out.println(loadPrice("49o"));
        } catch (DataLoadException e) {
            System.out.println(e.getMessage());
            System.out.println("caused by " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
            StackTraceElement top = e.getStackTrace()[0];
            System.out.println("thrown in " + top.getMethodName());
        }
    }
}

Output

499
bad price in feed: '49o'
caused by NumberFormatException: For input string: "49o"
thrown in loadPrice

Assertions

assert condition : message; documents and checks an assumption during development and testing. Assertions are off by default and enabled with java -ea; when one fails it throws AssertionError. Never use them to validate user input or arguments of public methods – that must work in production too.

public class Main {
    // assert checks an assumption that must ALWAYS be true if the code is correct.
    // Assertions are disabled by default; enable them with: java -ea Main
    static int percentage(int part, int total) {
        assert total > 0 : "total must be positive, was " + total;
        int p = part * 100 / total;
        assert p >= 0 && p <= 100 : "percentage out of range: " + p;
        return p;
    }

    public static void main(String[] args) {
        boolean enabled = false;
        assert enabled = true;                          // a common trick to detect whether -ea is on
        System.out.println("assertions enabled: " + enabled);
        System.out.println(percentage(45, 60));
        try {
            System.out.println(percentage(80, 50));
        } catch (AssertionError e) {                    // AssertionError is an Error, not an Exception
            System.out.println("AssertionError: " + e.getMessage());
        }
    }
}

Output

assertions enabled: true
75
AssertionError: percentage out of range: 160

Common mistakes

  • Empty catch blocks that silently swallow errors.
  • Catching Exception or Throwable everywhere instead of specific types.
  • A superclass catch before a subclass catch.
  • Returning from finally – it hides exceptions and earlier returns.
  • Losing the cause when wrapping exceptions.
  • Using exceptions for normal control flow.
  • Forgetting to close resources – use try-with-resources.
  • Using assert to check user input.

Key points to remember

  • Throwable → Error and Exception; RuntimeException is unchecked.
  • Checked exceptions must be caught or declared with throws.
  • Catch specific types first; multi-catch handles unrelated types together.
  • finally always runs (except when the JVM exits).
  • try-with-resources closes AutoCloseable resources in reverse order.
  • Wrap with a cause; never swallow exceptions silently.

Frequently asked questions

Does finally always run?

Yes, except if the JVM stops – for example System.exit(), a crash, or an infinite loop in try.

Should I catch NullPointerException?

Generally no – fix the bug (check for null, use Optional) rather than catching it.

Can a try have only finally?

Yes: try { … } finally { … } is legal; the exception still propagates after finally runs.

Where can I learn more?

Read Java Exception Handling and Java Custom Exceptions, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links