Wednesday, February 16, 2011

Javadoc all exceptions

All exceptions thrown by a method can be documented with the @throws javadoc comment (same as @exception). Some argue that an @throws should be included for every thrown exception, since it is the only way to clearly state all requirements made upon the caller (the pre-conditions). However, others disagree.

If all null object parameters passed to class methods cause a NullPointerException, then it is acceptable to state this once in the class javadoc comment, instead of repeating it for every method. Another alternative is to state in overview.html (javadoc's summary description of an application) that all parameters are to be considered as non-null unless explicitly stated otherwise.

Example

This example has an unusually large number of pre-conditions. Remarks regarding NullPointerException are placed in the class level javadoc comment.

Note that the unchecked SecurityException is thrown indirectly, through the calls to the methods of the File class.

import java.io.*;
/**
* If a null object parameter is passed to any method, then a
* <code>NullPointerException</code> will be thrown.
*/
public class WriteTextFile {
  //..other methods elided
  /**
  * Change the contents of a text file in its entirety, overwriting any
  * existing text.
  *
  * @param aFile is an existing file (not a directory) which can be written.
  * @param aContents is the text to be placed into aFile.
  *
  * @exception FileNotFoundException if aFile does not exist.
  * @exception IOException if stream to aFile cannot be written to or closed.
  *
  * @exception IllegalArgumentException if aFile is a directory.
  * @exception IllegalArgumentException if aFile cannot be written.
  * @exception SecurityException if a SecurityManager exists and
  * disallows read or write access to aFile.
  */
  static public void setContents(File aFile, String aContents)
                                 throws FileNotFoundException, IOException {
    if (aFile == null) {
      throw new NullPointerException("File must not be null.");
    }
    if (aContents == null) {
      throw new NullPointerException("Contents must not be null.");
    }
    if (!aFile.exists()) {
      throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
      throw new IllegalArgumentException("Must not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
      throw new IllegalArgumentException("File cannot be written: " + aFile);
    }
    Writer output =  new BufferedWriter( new FileWriter(aFile) );
    try {
      output.write( aContents );
    }
    finally {
      //flush and close both "output" and its underlying FileWriter
      output.close();
    }
  }
  public static void main (String... aArguments) throws IOException {
    File testFile = new File("C:\\Temp\\blah.txt");
    setContents(testFile, "blah blah blah");
  }
} 

No comments:

Post a Comment

Chitika