Java Notes

Exception Usage

Exceptions Exception Usage | Exceptions - More

Common Exceptions To Catch

The most common exceptions to catch are number conversion exceptions and I/O exceptions. Here are some common exceptions to catch:

Exception Cause
NumberFormatException You tried to convert a number from an illegal String form.
InputMismatchException A Scanner method, eg nextDouble() will throw this exception when the next input text is not the right type, eg double.
IOException Catch an IOException to get either of its subclasses below.
    FileNotFoundException The specified file didn't exist.
    EOFException Tried to read past end of file.
MalformedURLException This can be generated if you are using the java.net package.

Suggestions for catching exceptions

If you catch an exception, do something. Don't silence exceptions.
Some programs catch exceptions, then do nothing with them. This is almost always a mistake, and the underlying error should be fixed.

There are a few cases where you might want to silently ignore an exception. For example, changing the Look and Feel of the GUI may cause an exception. There's nothing to be done about it, so you don't want to stop execution. For example, I sometimes use the Liquid look and feel, and have this code.

try {
    UIManager.setLookAndFeel(new net.sourceforge.napkinlaf.NapkinLookAndFeel());
} catch (Exception e) {
    // Silently ignore -- there's nothing to be done.
}

Another example where exceptions are typically ignored is in calls to sleep.

try {
    Thread.sleep(DELAY);
} catch (InterruptedException ignoredException) {
    // Silently ignore.  This thread can never cause an exception.
}

If you do silently ignore exceptions, enclose only one call in the try clause; do not use larger blocks of code as suggested below. Rather than silently ignoring exceptions, consider logging them to a file.

Put larger blocks of code in a try clause
Altho an exception is generated by a single statement, an entire block of code is usually affected. It is often better to put the try around the block, not just single statements.
Don't catch exceptions that you can't really do anything with
If you can't do anything useful, don't catch an exception. Let someone higher up catch it.
Exception handling is usually slow
It is generally not a good idea to use exception handling mechanism instead of simple if tests because throwing and catching exceptions is typically much slower.
Catch and rethrow exceptions to clean up
If your code has to clean up something (eg, close files, put a data structure into a consistent state, ...), it can catch exceptions, do the cleanup, and then rethrow the exception.

Printing the call stack

For debugging purposes you can print a trace of the current call stack.

e.printStackTrace();