Question

As I understand it, an IllegalArgumentException is intended to communicate a programming error.

If I'm writing a service layer that that is essentially accepting user input via a web service, if the web service is passing in an illegal argument provided by the client would IllegalArgumentException NOT be appropriate, since this isn't really a programming error? Would it be better to create my own service level exception?

Was it helpful?

Solution

Yes, a RuntimeException (and by extension, an IllegalArgumentException) should be used to make it clear that a programming error or some other unexpected or incorrect action has taken place. It should send an alarm that a bug has been uncovered, something that should be corrected and validated by testing.

But depending on how your design allocates responsibilities, it may make perfect sense for the service layer to throw an IllegalArgumentException. From a use case perspective, any time you are dealing with user input, you pretty much have to expect invalid values and deal with them gracefully. It is just an alternate path through the use case and something that is absolutely going to occur, so not really a bug.

But dealing with invalid user input is usually something that is the responsibility of the user interface, so a web page should gracefully deal with bad input and give the user a chance to make corrections (entering an incorrectly typed password during a login attempt, for example). But since that is expected, it's not really an exception. The key is that the user interface should not send an invalid request to the server if it is able to ensure validity before sending the request. If that is possible in the user interface, it makes sense for the service layer to throw an IllegalArgumentException.

Going back to the user login example, the user interface can only make sure the data entered is correctly formatted; it's totally unable to guarantee that the values are actually correct. So the user interface must send correctly formatted input to the service layer. In this kind of scenario, I wouldn't throw an exception from the service layer, because correctly formatted but incorrect values are an expected occurrence. In this case, I would throw an exception if the values sent by the user interface were incorrectly formatted, but not if the values were simply incorrect. In the second case, I would reply to the user interface saying that the values are incorrect, but I wouldn't throw an exception.

Hope this long answer is helpful -

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top