Exception Handling in Java

    Atul Kabra3 min readUpdated

    An exception is an event that disrupts the normal flow of a program — a missing file, a divide-by-zero, an out-of-range index. Java's exception handling lets you detect such problems and respond instead of crashing. The core tools are try, catch, and finally; you can also throw exceptions yourself and declare them with throws. Done well, exception handling keeps programs robust and gives users helpful messages instead of stack traces.

    try / catch

    Put risky code in a try block and handle the failure in a catch block.

    try {
        int[] nums = {1, 2, 3};
        System.out.println(nums[5]); // throws ArrayIndexOutOfBoundsException
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("That index does not exist: " + e.getMessage());
    }
    // Program continues instead of crashing.
    

    If the try block throws, Java jumps to the matching catch. The exception object (e) carries details such as a message.

    Catching multiple exceptions

    try {
        int result = Integer.parseInt("abc"); // NumberFormatException
    } catch (NumberFormatException | NullPointerException e) { // multi-catch
        System.out.println("Bad input: " + e.getMessage());
    }
    

    You can also use several catch blocks; Java tries them top to bottom, so put more specific exception types first.

    finally

    The finally block always runs — whether or not an exception occurred — making it the place to release resources.

    try {
        System.out.println("Doing work");
    } catch (Exception e) {
        System.out.println("Handled: " + e.getMessage());
    } finally {
        System.out.println("Always runs (cleanup here)");
    }
    

    Checked vs unchecked exceptions

    • Checked exceptions (e.g. IOException) represent recoverable, expected conditions. The compiler forces you to either catch them or declare them with throws.
    • Unchecked exceptions (subclasses of RuntimeException, e.g. NullPointerException, ArithmeticException) usually signal programming bugs and are not required to be declared.
    // 'throws' declares that this method may pass a checked exception to its caller.
    static void readFile(String path) throws java.io.IOException {
        // ... code that may throw IOException
    }
    

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Throwing your own exceptions

    Use throw to raise an exception when your code detects an invalid situation.

    static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative: " + age);
        }
        // ... proceed with a valid age
    }
    

    You can also define custom exception classes by extending Exception (checked) or RuntimeException (unchecked) for domain-specific errors.

    try-with-resources

    When you open something that must be closed (a file, a database connection), try-with-resources closes it automatically — even if an exception is thrown.

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    static void printFirstLine(String path) throws IOException {
        // The reader is declared in parentheses; Java closes it for you.
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            System.out.println(reader.readLine());
        } // reader.close() called automatically here
    }
    

    This is the modern, safe alternative to closing resources by hand in a finally block.

    Common mistakes

    • Catching Exception and doing nothing. An empty catch swallows errors silently. At minimum, log the problem.
    • Catching too broadly. Catch the specific exception you can handle; let unexpected ones propagate.
    • Using exceptions for normal control flow. They are for exceptional conditions, not for ordinary branching — use if for that.
    • Forgetting to close resources. Prefer try-with-resources over manual finally cleanup.
    • Order of catch blocks. A broad catch (Exception e) before a specific one makes the specific block unreachable and fails to compile.

    FAQ

    What is the difference between throw and throws? throw actually raises an exception; throws is a method-signature declaration warning callers that the method might throw one.

    Should I make my custom exception checked or unchecked? Use checked when callers can reasonably recover and you want to force handling; use unchecked for programming errors.

    Keep going

    Next, manage groups of objects with The Java Collections Framework, or revisit String Handling in Java. All tutorials are on the Java hub; for guided practice in Jalgaon, see the Java course.


    Write resilient programs at Infoplanet, Jalgaon. Join the waitlist for the Java course.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides