I’ll explain what I mean by input error checking.
Say you have a function doSomething(x).
If the function completes successfully doSomething does something and returns nothing. However, if there are errors I’d like to be notified. That is what I mean by error checking.
I’m looking for, in general, the best way to check for errors. I’ve thought of the following solutions, each with a potential problem.
-
Flag error checking. If
doSomething(x)completes successfully returnnull. Otherwise, it returns a boolean or an error string. Problem: Side effects. -
Throwing an exception. Throw an exception if
doSomething(x)encounters an error. Problem: If you are performing error checking for parameters only, throwing anIllegalArgumentExceptionseems inappropriate. -
Validating input prior to function call. If the error checking is only meant for the parameters of the function, then you can call a validator function before calling the
doSomething(x)function. Problem: What if a client of the class forgets to call the validator function before callingdoSomething(x)?
I often encounter this problem and any help or a point in the right direction would be much appreciated.
This is appropriate in some cases, depending on what you mean by an “error”.
An example from the API: If you try to add an object to a
Set, which already contains another object whichequalsthe new object, theaddmethod sort of “fails” and indicates this by returningfalse. (Note that we’re on a level at which it’s technically not even an “error”!)This is the default option.
Question is now, should you go for a checked exception (which you need a
throwsdeclaration ortry/catchclauses) or an unchecked exception (an exception that extendsRuntimeException). There are a few rules of thumbs here.From Java Practices -> Checked versus unchecked exceptions:
Unchecked exceptions: Represent defects in the program (bugs) – often invalid arguments passed to a non-private method.
Checked exceptions: Represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
Note that
IllegalArgumentExceptionis an unchecked exception, perfectly suitable for throwing when arguments are not as they should be.If you want to throw a checked exception, you could A) roll your own by extending
Exception, B) use some existing checked exception or C) “chain” a runtime exception in, for instance, anIOException:throw new IOException(new IllegalArgumentException("reason goes here..."));Relying on the fact that the client should have sanitized / checked his arguments before the call seems like a bad idea to me.