I wonder if using an IllegalStateException in this scenario is a good design choice for an API.
Scenario:
I have a function which checks if an XML document is well formed with the following signature:
public boolean isXMLDocumentWellFormed(InputStream inXMLDocument)
This function uses the following snippet to load the XML document:
boolean isXMLDocWellFormed = false;
// Setup document builder
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
if (docBuilderFactory == null)
throw new IllegalStateException(
"The DocumentBuilderFactory cannot be instanciated");
try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// Parse document
Document doc = docBuilder.parse(inXMLDocument);
if (doc != null)
isXMLDocWellFormed = true;
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new IllegalStateException(e);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new IllegalStateException(e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new IllegalStateException(e);
}
return isXMLDocWellFormed;
The API is designed to be very easy to use. However, I would like to provide to API users the possibility to know why an XML document cannot be checked (example: DocumentBuilderFactory cannot create a DocumentBuilder object) without overwhelming them with tons of checked exception that they will have to deal with.
My concerns regarding this design are:
a) Does using one single Exception type (i.e IllegalStateException) to return every possible caught exceptions to indicate a failure to perform the check a good idea ? I would say yes since users would except 2 things out of this function:
- To know if the XML document is well formed or not.
- To know in the event that the function cannot return the answer (due to an exception for instance) why the function failed to provide the answer.
b) If the answer to a) is no, then what would be the most appropriate exception name or solution and why ?
Regards,
If its an API that your developing then you should wrap all exceptions in one main exception. This way you don’t bleed implementation details. However your personal taste may differ
However I don’t think IllegalStateException fits well here. Its very generic and doesn’t explain the problem (An IO Exception is Illegal state?). Best solution is to create your own custom Exception class and throw that.
As a side node to you or anyone else, please don’t print the exception if your throwing it.