Which exception to throw for invalid input which is valid from client perspective

The question is is throwing illegal argument exception the right thing to do?

It depends on how you want / need to “frame” this condition; i.e. is it a bug, a user input error, or something that the program is supposed to be able to deal with?

  • If the case of two lines not intersecting is unequivocally a “bug”, then IllegalArgumentException is fine. This is what the exception is designed for. (Note that it is an unchecked exception, so the expectation is that it won’t be caught / recovered from.)
  • If this is a case that you expect the program to be able to recover from by itself, then a custom exception is the best idea. That way, you reduce the possibility of your code getting confused by (say) a library method throwing (say) an IllegalArgumentException … than means something other than “two lines intersected”.
  • If this case is something that you expect to report to the end user as part of input validation, then a generic “validation error” exception might be more appropriate than a specific custom exception. However, this method doesn’t look like it is designed to be used (solely) for user input validation.

In some contexts, it may be better to not throw an exception at all, but (IMO) this is not one of those contexts. The alternatives are returning null or returning a Point value that means “no such point” to the calling code. The problems with the alternatives are:

  • If you return null the application has to deal with the null case … or there will be NPEs.
  • There is no natural Point instance that could be used to mean “not a point”.

This is not to say that you couldn’t make these alternatives work. It is just that in this context, it will probably be more work to do that, and probably there won’t be a tangible pay-off.

Leave a Comment