2

What kind of exception should I throw if the XML can be parsed, but is not structured in the way expected by the program - wrong tag names etc.

Example - Expected

<xml>
 <tag1>blabla</tag1>
 <tag2> <tag3>blabla </tag3> </tag2>
</xml>

Example - actual

<xml>
 <tag1>blabla</tag1>
 <tag2> blabla </tag2>
</xml>

Is there a standard exception for this case? The question concerns Java, I am using the standard javax.xml classes for parsing.

4
  • 5
    IllegalArgumentException. Assuming the XML itself is valid, then the value passed isn't what was expected, which puts it into any other scenario where the input is not what was expected. But if you feel that isn't explicit enough, write a custom exception.
    – Neil
    May 15 '18 at 9:59
  • @Neil I followed the approach of explicitly writing out the schema and using the java.xml.validation classes to validate my xml. Thanks for your answer.
    – kutschkem
    May 15 '18 at 12:56
  • What does it matter? You are going to kill the app anyway, who cares what the exact name of that lethal act was?
    – David Arno
    May 15 '18 at 19:04
  • @DavidArno The poor guy debugging it?
    – kutschkem
    May 16 '18 at 6:33
2
  • You can give a look to SAXParseException if you think it matches your requirements. It is included in the JDK it is hence available without any external dependency. It is a checked Exception, so, you'll be able to force the callers of your code to explicitly catch the exception.

  • If you're parsing the XML with some library, and you have an XSD or a DTD, there are high chances the library itself already offer an exception that is usually thrown when parsing fails.

  • Otherwise you can choose to wrap whatever exception reaised by the parsing library in a more business oriented custom exception, i.e. InvalidXmlException.

  • I think @neil advice is great if the XML is an input of your system. If you use such XML for other meanings, like configuration, maybe an InvalidStateException is better suited ?

Regardless of what you choose, be aware of these:

  • try not to introduce unwanted dependencies to external libraries, if possible;
  • document in your javadoc when the exception is throw in order to allow callers to properly understand how to catch the exception.
4
  • The term 'malformed XML' isn't appropriate here. The XML is well-formed it just doesn't match the expected structure.
    – JimmyJames
    May 15 '18 at 13:46
  • Thx @JimmyJames I completely agree with you. I edidted my answer accordingly.
    – danidemi
    May 15 '18 at 14:31
  • The link is broken, there is an extra = at the end that shouldn't be there.
    – kutschkem
    May 16 '18 at 11:17
  • Thx @kutschkem, I've just edited the answer fixing the typo.
    – danidemi
    May 17 '18 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.