11.4 An Example of Exceptions

Consider the following example:

class TestException extends Exception {

  TestException() { super(); }


    TestException(String s) { super(s); }

}

class Test {

    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            try {
                thrower(args[i]);
                System.out.println("Test \"" + args[i] +
                    "\" didn't throw an exception");
            } catch (Exception e) {
                System.out.println("Test \"" + args[i] +
                    "\" threw a " + e.getClass() +
                    "\n        with message: " + e.getMessage());
            }
        }
    }


    static int thrower(String s) throws TestException {
        try {
            if (s.equals("divide")) {
                int i = 0;
                return i/i;
            }
            if (s.equals("null")) {
                s = null;
                return s.length();
            }
            if (s.equals("test"))
                throw new TestException("Test message");
            return 0;
        } finally {
            System.out.println("[thrower(\"" + s +
                    "\") done]");
        }
    }
}

If we execute the test program, passing it the arguments:

divide null not test

it produces the output:

[thrower("divide") done]
Test "divide" threw a class java.lang.ArithmeticException
        with message: / by zero
[thrower("null") done]
Test "null" threw a class java.lang.NullPointerException
        with message: null
[thrower("not") done]
Test "not" didn't throw an exception
[thrower("test") done]
Test "test" threw a class TestException
        with message: Test message

This example declares an exception class TestException. The main method of class Test invokes the thrower method four times, causing exceptions to be thrown three of the four times. The try statement in method main catches each exception that the thrower throws. Whether the invocation of thrower completes normally or abruptly, a message is printed describing what happened.

The declaration of the method thrower must have a throws clause because it can throw instances of TestException, which is a checked exception class (ยง11.2). A compile-time error would occur if the throws clause were omitted.

Notice that the finally clause is executed on every invocation of thrower, whether or not an exception occurs, as shown by the "[thrower(...) done]" output that occurs for each invocation.