Java

Advantages of Exception Handling in Java (With Examples)

Updated October 2026. Every example was run on Java 21.

The main advantages of exception handling in Java are that your program can recover from errors and keep running, your normal code stays separate from error code, errors travel up the call stack to the right place, error messages are descriptive, and exceptions can be grouped by type.

Below, each advantage comes with a short example and its real output. That way, you can see the difference instead of taking it on trust.

The 5 advantages at a glance

# Advantage What it gives you
1 The program can keep running One failure does not stop everything
2 Normal code and error code stay apart Code that is easier to read and maintain
3 Errors propagate up the call stack You handle an error where you can actually deal with it
4 Errors carry meaningful information Faster debugging
5 Exceptions can be grouped by type Specific handling where needed, general handling elsewhere

1. The program can keep running after an error

First, here is a loop that divides 100 by each number in an array, with no exception handling:

WRONG

public class WithoutHandling {

    public static void main(String[] args) {
        int[] divisors = {5, 0, 2, 0, 10};

        for (int divisor : divisors) {
            int result = 100 / divisor;
            System.out.println("100 / " + divisor + " = " + result);
        }

        System.out.println("Program finished normally.");
    }
}

Output:

100 / 5 = 20
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at WithoutHandling.main(WithoutHandling.java:7)

The first zero stops the whole program. As a result, the remaining numbers are never processed, and the last line never prints.

Now wrap the risky line in try and catch. Then run it again:

RIGHT

public class KeepRunning {

    public static void main(String[] args) {
        int[] divisors = {5, 0, 2, 0, 10};

        for (int divisor : divisors) {
            try {
                int result = 100 / divisor;
                System.out.println("100 / " + divisor + " = " + result);
            } catch (ArithmeticException e) {
                System.out.println("Skipping divisor " + divisor + ": " + e.getMessage());
            }
        }

        System.out.println("Program finished normally.");
    }
}

Output:

100 / 5 = 20
Skipping divisor 0: / by zero
100 / 2 = 50
Skipping divisor 0: / by zero
100 / 10 = 10
Program finished normally.

This time the loop carries on after each failure. However, an exception that nobody catches still ends the program, so the catch block is what makes recovery possible.

2. Normal code and error-handling code stay apart

Without exceptions, you check for every problem along the way and return an error code. Because of this, the real work gets buried in the checks. With exceptions, however, the main path stays clean and you handle errors in one place.

// Style 1: error codes mixed into the main logic
static String readWithCodes(String file) {
    Path path = Path.of(file);
    if (!Files.exists(path)) {
        return "ERROR: file not found";
    }
    if (!Files.isReadable(path)) {
        return "ERROR: file not readable";
    }
    try {
        return Files.readString(path);
    } catch (IOException e) {
        return "ERROR: read failed";
    }
}

// Style 2: main logic first, error handling kept separate
static String readWithExceptions(String file) throws IOException {
    return Files.readString(Path.of(file));
}

Calling both with a file that does not exist:

Codes     : ERROR: file not found
Exception : java.nio.file.NoSuchFileException: missing.txt

Style 2 is one line, and the caller decides what to do with the problem. In style 1, on the other hand, the caller has to remember that the string "ERROR: ..." might be an error message and not file content. Worse, nothing forces it to check.

3. Errors propagate up the call stack

The method where an error happens is often not the right place to deal with it. Fortunately, with exceptions the error moves up through the calling methods until something catches it.

public class Propagation {

    static void level3() {
        int[] numbers = new int[3];
        numbers[5] = 1;                  // throws here
    }

    static void level2() {
        level3();                        // no try/catch, the exception passes through
    }

    static void level1() {
        level2();                        // no try/catch either
    }

    public static void main(String[] args) {
        try {
            level1();
        } catch (ArrayIndexOutOfBoundsException e) {   // handled here, three levels up
            System.out.println("Caught in main: " + e.getMessage());
            e.printStackTrace(System.out);
        }
    }
}

Output:

Caught in main: Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    at Propagation.level3(Propagation.java:5)
    at Propagation.level2(Propagation.java:9)
    at Propagation.level1(Propagation.java:13)
    at Propagation.main(Propagation.java:18)

level2 and level1 contain no error-handling code at all, yet the error still reaches main. In addition, the stack trace shows the exact path it took. (If you run this with the single-file java Propagation.java launcher, a few extra lines from the launcher appear after these four.)

4. Errors carry meaningful information

An exception is an object, so it has a type, a message, a stack trace, and an optional cause. A bare error code like -1 tells you almost nothing. An exception, on the other hand, tells you what went wrong and where.

static int parseAge(String text) {
    try {
        return Integer.parseInt(text);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Age must be a whole number, got: '" + text + "'", e);
    }
}

Calling parseAge("twenty") and printing the details:

Message : Age must be a whole number, got: 'twenty'
Cause   : java.lang.NumberFormatException: For input string: "twenty"
toString: java.lang.IllegalArgumentException: Age must be a whole number, got: 'twenty'

If you pass the original exception e as the cause, you keep the full history. So nothing is lost when you wrap it in a clearer one.

5. Exceptions can be grouped by type

Java organises exceptions in a class hierarchy. For example, FileNotFoundException is a kind of IOException, so you can handle the specific case first and everything else with the general one.

try {
    open("missing.txt");
} catch (FileNotFoundException e) {      // specific subclass first
    System.out.println("Specific : file not found -> " + e.getMessage());
} catch (IOException e) {                // general superclass second
    System.out.println("General  : some other I/O problem -> " + e.getMessage());
}

Output:

Specific : file not found -> missing.txt (No such file or directory)

The order matters. If you put the general IOException first, the specific block can never run. For that reason, the compiler stops you:

WrongOrder.java:11: error: exception FileNotFoundException has already been caught
        } catch (FileNotFoundException e) {      // never reachable
          ^

Finally, if two exception types need the same handling, join them with |, as in catch (IOException | SQLException e).

Common mistakes

  • Empty catch blocks. catch (Exception e) {} hides the problem. At the very least, log the exception.
  • Catching Exception or Throwable everywhere. Otherwise you also catch bugs you never meant to handle. Instead, catch the most specific type you can deal with.
  • Putting the general exception first. Because the specific catch becomes unreachable, the code does not compile.
  • Losing the original cause. When you wrap an exception, pass the original as the cause.
  • Using exceptions for normal flow. Do not throw an exception to end a loop or to return a value. Instead, use it only for real error conditions.

Summary

In short, exception handling lets a program recover from errors, keeps the normal code readable, and sends each error to the code best placed to handle it. It also describes what went wrong and lets you treat different problems differently. As a result, your programs become easier to debug and more reliable.

References

Related posts

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Java

What is Exception in Java

Exception: A statement which is capable of terminating a program abruptly at runtime is known as Exception. In Java they have identified all the possible situations that are…

Java

How do we Handle Exception in Java

Exception Handling in Java In the previous tutorial, we have discussed what is an Exception and the different types of exceptions in Java. In this tutorial, we are…

5 comments

  1. An Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.

Ask a question or leave a comment