Throwing new Exceptions

TestExceptions.java

In TestExceptons.java, we have four methods, each of which is equally likely to throw an exception. We catch the exception at a high level, and throw a new exception with a user-friendly message.

Unfortunately, no matter which method throws the original exception, our stack trace is always the same:

Running: c:\jdk1.3\bin\java -mx64m TestExceptions

java.lang.Exception: Oh, no!
    at TestExceptions.thisWillFail(TestExceptions.java:18)
    at TestExceptions.main(TestExceptions.java:8)

0 error(s)
import java.util.Random;

public class TestExceptions {
    static final Random random = new Random();

    public static void main(String[] args) {
        try {
            thisWillFail();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void thisWillFail() throws Exception {
        try {
            methodOne();
        } catch (Exception e) {
            throw new Exception("Oh, no!");
        }
    }

    static void methodOne() throws Exception {
        if (random.nextGaussian() > 0.67) {
            throw new Exception();
        }
        methodTwo();
    }

    static void methodTwo() throws Exception {
        if (random.nextGaussian() > 0.43) {
            throw new Exception();
        }
        methodThree();
    }

    static void methodThree() throws Exception {
        if (random.nextGaussian() > 0.0) {
            throw new Exception();
        }
        methodFour();
    }

    static void methodFour() throws Exception {
        throw new Exception();
    }
}