4

In have written a function which expects the caller to pass in a configuration file like XML. Then I parse this given file and extract something which i then return.

In this function (at least) two "bad" things can happen:

  1. The given file does not exist or is not accessible in any way
  2. While parsing/validating the file some unexpected content is found

The first thing is clearly an IllegalArgumentException. I am however not sure what kind of exception the second case would be. Is that also an IllegalArgumentException because i expect (by documentation-contract) that the input is in a valid form? Or is it rather an IllegalStateException as the given parameter is formal correct but only after parsing I can't do any further steps as it would result in unwanted behaviour?

Or is it even something else?

  • 1
    I think you're splitting hairs here... – Ampt Jun 27 '14 at 13:30
  • if you prefer JDK style design, consider that SAXParser.parse and DocumentBuilder.parse throw custom exceptions inherited directly from Exception not from ISE – gnat Jun 27 '14 at 13:32
  • Technically problems derived from information gathered from a parameter, even indirectly, is considered to be an IllegalArgumentException, so long as the nature of gathering this information is entirely unexpected. For example, file not found is certainly something which is not expected, however attempting a connection to a database could go wrong, and thus shouldn't fall under IllegalArgumentException imho. – Neil Jun 27 '14 at 13:46
  • Perhaps you would consider a custom exception for your application, some kind of InvalidContentException? – FrustratedWithFormsDesigner Jun 27 '14 at 15:08
  • IllegalStateException could be more meaningful if you have had a boolean variable enableParsing to false, and then invoked the method to parse a file. This is an illegal state. – bbalchev Jun 27 '14 at 16:07
3

Neither. As others have pointed out, it is clearly not an IllegalStateException.

And better than IllegalArgument would be FileNotFoundException or ParseException, (or maybe XMLParseException) which exactly match your description of "bad things" 1 and 2.

9

The Javadocs of IllegalStateException say

Signals that a method has been invoked at an illegal or inappropriate time

I would argue, that it does not matter when your method is called or in what state the JVM or your context is - the parsing error will remain as long as the file is not correct. So it seems to me, that an IllegalArgumentException is more appropriate.

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.