Effective Exception Handling :: Console Applications

This is essentially anything that has a main method, where all execution happens within the Main thread. Very few enterprise applications execute in this way, but it is still a common way of testing new concepts or libraries.

1. Understand

So what happens when you don't catch any exceptions? Consider the following example which raises an unchecked ArithmeticException:

public class ConsoleTest {

    public static void main(String[] args) {
        int result = calculate(1, 0);
        System.out.println(result);
    }

    private static int calculate(int x, int y) {
        return x / y;
    }
}

This is what happens:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ConsoleTest.calculate(ConsoleTest.java:9)
        at ConsoleTest.main(ConsoleTest.java:4)

2. Evaluate

If we're writing such an application to test a new library as mentioned above, then this is ideal. For almost no effort, we get a message that tells us:

3. Implement

I wouldn't change a thing with this approach. I have seen people commonly do the following which is utterly redundant:

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

It requires more lines of code but produces exactly the same result as the following:

    public static void main(String[] args) {
        doSomethingThatMightFail();
    }

Additional Notes

I'm deliberately using examples that may throw unchecked exceptions which are not declared and do not need to be caught. This makes illustrating the process a lot simpler. One question that might be asked is how to deal with code that throws checked exceptions. The compiler will complain if we don't catch them.

In such cases the calling method will need to have a throws clause in order to propagate the exception. Here is an example:

public static void main(String[] args) throws Exception {
    doSomethingThatDeclaresCheckedExceptions();
}

It is considered by some to be lazy coding to use a blanket throws Exception clause. Personally, I don't have a problem with it in throw-away applications such as the one above. It generally isn't a good idea when writing libraries that will be used in another application.

This is one criticism I have of the Java language, and something that Microsoft got right with C# - doing away with checked exceptions altogether. They only seem to encourage people to litter their code with catch blocks.

Coming Soon: Swing Applications