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:
- No more boilerplate text when documenting exceptions.
- The intent of the exception is clearly communicated via a factory method.
- We are hiding the complexity of the exception’s declaration behind a consistent exterior.