Documenting Exceptions via Factory Methods

May 28th, 2008

Jesse described a technique for handling methods that always throws. This is a very interesting technique. Having written that, would it not be nice to encourage the use of this technique, in our Java coding conventions, as a way to document DRY exceptions? Honestly, I’d’ think we should. It would prevent us from repeating the same description of our exceptions numerous times in our JavaDocs… Disclaimer: this is just a very simple example that tries to convey my point :)


/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
  try {
     //.... some code goes here to
     //.... load a config file.
  } catch (RuntimeException re){
	throw unableToFindConfigFile(
           "loadConfig():void",
           re
        );
  }
}

/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
   try {
	//.... some code goes here to load
	//.... a config file.
    } catch (RuntimeException re){
	throw unableToFindConfigFile(
		"loadConfig():void",
		re
	);
    }
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

Some of this approach’s benefits:

  1. No more boilerplate text when documenting exceptions.
  2. The intent of the exception is clearly communicated via a factory method.
  3. We are hiding the complexity of the exception’s declaration behind a consistent exterior.

programming, random ideas | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

May 2008
M T W T F S S
« Apr   Jun »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Archives

Tags