Skip to lesson

Chain exceptions with a cause

A payment fails deep inside a database driver, but your screen only shows "Payment failed". If the original error is thrown away, nobody can find the real reason later.

Constructors that take a cause

Exception chaining wraps a low-level exception inside a higher-level one as its cause, so the stack trace keeps the original reason.

Most exception classes have a constructor (String message, Throwable cause) that stores another exception as the cause. Exception, RuntimeException, IOException, IllegalStateException and IllegalArgumentException all have it.

A chain of three exceptions. main catches ReportException. Its cause, from getCause(), is IllegalArgumentException, and that exception was caused by NumberFormatException, the root cause. A stack trace prints each level after "Caused by".

Example 1 · Wrap a low-level exception with a cause

WrapWithCauseDemo.javaJava
class ResultLoadException extends Exception {    ResultLoadException(String message, Throwable cause) {        super(message, cause);    }}
public class WrapWithCauseDemo {    static int loadMarks(String roll, String rawMarks) throws ResultLoadException {        try {            return Integer.parseInt(rawMarks);        } catch (NumberFormatException e) {            throw new ResultLoadException("could not load marks for " + roll, e);        }    }
    public static void main(String[] args) {        try {            System.out.println("CS101: " + loadMarks("CS101", "88"));            System.out.println("CS102: " + loadMarks("CS102", "9O"));        } catch (ResultLoadException e) {            System.out.println("Error: " + e.getMessage());            System.out.println("Cause: " + e.getCause());        }    }}
Output
CS101: 88
Error: could not load marks for CS102
Cause: java.lang.NumberFormatException: For input string: "9O"

What this code does

  • ResultLoadException passes both values to super(message, cause), so it inherits the cause support built into Throwable.
  • The caller gets a message about the student, and getCause() still gives the original NumberFormatException with the exact bad text.

You wrap when the low-level exception does not make sense to the caller. A results page that gets NumberFormatException: For input string: "9O" learns nothing useful. ResultLoadException: could not load marks for CS101, with that NumberFormatException as its cause, explains what failed and still keeps why. Your own exception class gets the same power with one line: a constructor that passes both values to super(message, cause).

There is also a constructor that takes only the cause: new RuntimeException(cause). Its message becomes the cause's toString(), such as java.lang.NumberFormatException: For input string: "9O".

getCause and initCause

getCause() returns the exception stored as the cause, or null when there is none. It is defined in Throwable, so every exception and error has it.

Example 2 · getCause and initCause

InitCauseDemo.javaJava
class OldStyleException extends Exception {    OldStyleException(String message) {   // no cause constructor        super(message);    }}
public class InitCauseDemo {    public static void main(String[] args) {        IllegalArgumentException low = new IllegalArgumentException("fee cannot be negative");
        OldStyleException e = new OldStyleException("fee update failed");        System.out.println("before: " + e.getCause());
        e.initCause(low);        System.out.println("after:  " + e.getCause().getMessage());
        try {            e.initCause(new IllegalStateException("second cause"));        } catch (IllegalStateException again) {            System.out.println("second initCause: " + again.getClass().getSimpleName());        }
        RuntimeException withCause = new RuntimeException("sync failed", low);        try {            withCause.initCause(low);        } catch (IllegalStateException again) {            System.out.println("initCause after constructor: " + again.getClass().getSimpleName());        }    }}
Output
before: null
after:  fee cannot be negative
second initCause: IllegalStateException
initCause after constructor: IllegalStateException

What this code does

  • OldStyleException has no cause constructor, so initCause sets the cause after creation. Before that, getCause() returns null.
  • A cause can be set only once. The second initCause, and an initCause after a constructor that took a cause, both throw IllegalStateException.

initCause(cause) sets the cause after the object is created. You need it only for an exception class with no cause constructor. It works once: calling it a second time, or after a constructor already set a cause (even null), throws IllegalStateException.

Finding the root cause with a loop

Causes can be chained many levels deep: a report fails because a row failed because a number did not parse. The root cause is the last exception in that chain, the one with no cause of its own. It usually names the real problem.

Java
static Throwable rootCause(Throwable t) {    while (t.getCause() != null) {        t = t.getCause();    }    return t;}

To reach it, follow getCause() in a loop until it returns null. Each step moves one level down, from the general message towards the specific one.

Example 3 · Walk a three-level chain to the root

RootCauseDemo.javaJava
class ReportException extends Exception {    ReportException(String message, Throwable cause) {        super(message, cause);    }}
public class RootCauseDemo {    static int parseRow(String row) {        try {            return Integer.parseInt(row.split(",")[1]);        } catch (NumberFormatException e) {            throw new IllegalArgumentException("bad marks row: " + row, e);        }    }
    static int buildReport(String[] rows) throws ReportException {        int total = 0;        try {            for (String row : rows) {                total += parseRow(row);            }        } catch (IllegalArgumentException e) {            throw new ReportException("could not build class report", e);        }        return total;    }
    static Throwable rootCause(Throwable t) {        while (t.getCause() != null) {            t = t.getCause();        }        return t;    }
    public static void main(String[] args) {        String[] rows = {"Asha,81", "Ravi,7x", "Meena,90"};        try {            System.out.println("Total: " + buildReport(rows));        } catch (ReportException e) {            int level = 0;            for (Throwable t = e; t != null; t = t.getCause()) {                System.out.println("level " + level + ": " + t.getClass().getSimpleName() + ": " + t.getMessage());                level++;            }            System.out.println("root cause: " + rootCause(e).getMessage());        }    }}
Output
level 0: ReportException: could not build class report
level 1: IllegalArgumentException: bad marks row: Ravi,7x
level 2: NumberFormatException: For input string: "7x"
root cause: For input string: "7x"

What this code does

  • Each layer adds its own message and passes the exception it caught as the cause: number → row → report.
  • The for loop prints the whole chain from the top; rootCause follows getCause() until it reaches the exception with no cause, which names the real problem.

Losing the original error by not passing the cause

The most common chaining bug is to forget to pass the cause: throw new ResultLoadException("could not load marks"); inside a catch. The new exception has a good message, but getCause() returns null, and the stack trace no longer shows where the real failure happened.

Example 4 · Forgetting the cause

LostCauseDemo.javaJava
public class LostCauseDemo {    static int parseFee(String text) {        try {            return Integer.parseInt(text);        } catch (NumberFormatException e) {            throw new IllegalStateException("fee file is damaged");   // cause not passed        }    }
    static int parseFeeFixed(String text) {        try {            return Integer.parseInt(text);        } catch (NumberFormatException e) {            throw new IllegalStateException("fee file is damaged", e);        }    }
    public static void main(String[] args) {        try {            parseFee("45,000");        } catch (IllegalStateException e) {            System.out.println("without cause: " + e.getMessage() + " | cause = " + e.getCause());        }        try {            parseFeeFixed("45,000");        } catch (IllegalStateException e) {            System.out.println("with cause:    " + e.getMessage() + " | cause = " + e.getCause());        }    }}
Output
without cause: fee file is damaged | cause = null
with cause:    fee file is damaged | cause = java.lang.NumberFormatException: For input string: "45,000"

What this code does

  • Both messages say the file is damaged, but only the fixed version says why: the comma in "45,000".
  • Without the cause, anyone reading the error has to guess or reproduce the problem. Adding , e costs nothing and keeps all the details.

Copying only the text, as in new RuntimeException(e.getMessage()), is almost as bad. The message survives, but the original type and its trace are gone. Always pass the caught exception itself as the cause.

Example 5 · Putting it together: a UPI payment with a cause chain

UpiChainDemo.javaJava
import java.io.IOException;
class PaymentException extends Exception {    PaymentException(String message, Throwable cause) {        super(message, cause);    }}
class BankClient {    void debit(String upiId, int amount) throws IOException {        if (amount > 2000) {            throw new IOException("bank server closed the connection");        }        System.out.println("bank: debited Rs " + amount + " for " + upiId);    }}
class PaymentService {    private final BankClient bank = new BankClient();
    void pay(String upiId, int amount) throws PaymentException {        try {            bank.debit(upiId, amount);        } catch (IOException e) {            throw new PaymentException("payment of Rs " + amount + " to " + upiId + " failed", e);        }    }}
public class UpiChainDemo {    public static void main(String[] args) {        PaymentService service = new PaymentService();        int[] amounts = {150, 3500};        for (int amount : amounts) {            try {                service.pay("canteen@upi", amount);                System.out.println("app: payment successful");            } catch (PaymentException e) {                System.out.println("app: " + e.getMessage() + ". Please try again.");                Throwable root = e;                while (root.getCause() != null) {                    root = root.getCause();                }                System.out.println("log: root cause = " + root);            }        }    }}
Output
bank: debited Rs 150 for canteen@upi
app: payment successful
app: payment of Rs 3500 to canteen@upi failed. Please try again.
log: root cause = java.io.IOException: bank server closed the connection

What this code does

  • Each layer speaks its own language: the bank client talks about connections, the payment service talks about payments, and the app talks to the user.
  • The user sees a clear message, while the log line keeps the technical root cause for the developer. Both come from the same chained exception.

Next step

Check your understanding

12 quick questions