Avoid empty catch blocks in Java

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.


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 :
  • inform the user (strongly recommended)
  • log the problem, using the JDK logging services, or similar tool
  • send an email describing the problem to an administrator
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.


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 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    }
  }
} 


0 comments: