Home Java Java-tips Flow Exceptions Exception Usage

Ask Questions?

View Latest Questions


 
 

Exception Usage
Posted on: July 26, 2006 at 12:00 AM
The most common exceptions to catch are number conversion exceptions and I/O exceptions.

Java Notes

Exception Usage

Exceptions Exception Usage | Exceptions - More

Common Exceptions

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.

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("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) {
    //