Be specific in throws clause

In the throws clause of a method header, be as specific as possible. Do not group together related exceptions in a generic exception class - that would represent a loss of possibly important information.

An alternative is the exception translation practice, in which a low level exception is first translated into a higher level exception before being thrown out of the method.

Example

Here, both IOException and FileNotFoundException are incorrectly lumped together as Exception.


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

public final class BadGenericThrow {
  
  //..elided

  /**
  * BAD: This method throws a generic Exception, instead
  * of FileNotFoundException and IOException.
  */
  public void makeFile() throws Exception {
    //create a Serializable List
    List<String> quarks = new ArrayList<>();
    quarks.add("up");
    quarks.add("down");
    quarks.add("strange");
    quarks.add("charm");
    quarks.add("top");
    quarks.add("bottom");

    //serialize the List
    try (
      ObjectOutputStream output  = new ObjectOutputStream(
        new FileOutputStream("quarks.ser")
      )
    ){
      output.writeObject(quarks);
    }
  }
} 



See Also :
Exception translation
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -