Should I put throws IllegalArgumentException at the function?

Ismail Marmoush picture Ismail Marmoush · Mar 14, 2011 · Viewed 16.6k times · Source

I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException class as it seemed right name for the issue, but should I put the throws IllegalArgumentException at the function definition ?

I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.

Answer

ILMTitan picture ILMTitan · Mar 14, 2011

RuntimeExceptions like IllegalArgumentException are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.

Potential RuntimeExceptions should be documented somehow in the function contract (i.e. javadoc), either with the explicit @throws, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.

If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.