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 |
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. |
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("com.birosoft.liquid.LiquidLookAndFeel");
} 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.
try clauseif tests because throwing and
catching exceptions is typically much slower.
For debugging purposes you can print a trace of the current call stack.
e.printStackTrace();