Avoid empty catch blocks

Most contend that it's usually a very bad idea to have an empty catch block.

When the exception occurs, nothing happens, and the program fails for unknown reasons.

Example

The "tried our best" comments below are an example of what not to do :


import java.io.*;
import java.util.*;

/** How NOT to implement a catch.  */
public final class BadCatch {

  public static void main( String... arguments ) {
    List<String> quarks = Arrays.asList(
      "up", "down", "charm", "strange", "top", "bottom"
    );   

    //serialize the List
    try {
      ObjectOutputStream output =  new ObjectOutputStream(
        new FileOutputStream("quarks.ser")
      );
      try{
        output.writeObject(quarks);
      }
      finally{
        //flush and close all streams
        output.close();
      }
    }
    catch(IOException exception){
      //TRIED OUR BEST
    }
  }
} 

In general, when a exception occurs, it can be thrown up to the caller, or it can be caught in a catch block. When catching an exception, some options include :

Deciding what exactly to do seems to depend on the nature of the problem. If there is an actual bug in the program - a defect that needs to be fixed - then one might do all three of the above. In this case, the end user should likely be shown a generic "Sorry, we goofed" message, not a stack trace. It is usually considered bad form to display a stack trace to a non-technical end user, or if exposing a stack trace may be a security risk.

If the exception does not represent a bug, then different behavior may be appropriate. For example, if a problem with user input is detected and an exception is thrown as a result, then merely informing the user of the problem might be all that is required. For example, a message might read :

Cannot connect to database.

See Also :
Logging messages
Avoid basic style errors
Would you use this technique?
Yes   No   Undecided   
© 2010 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual code snippets can be used under this BSD license - Last updated on June 5, 2010.
Over 150,000 unique IPs last month - Built with WEB4J.
- In Memoriam : Bill Dirani -