I'm new to programming and am learning Java as my first oo language, by working through Introduction to Programming Using Java by David J. Eck and reading forum posts when stuck.
My question could be considered a follow-up to Java Class Constructor Parameters with range limits which deals with limiting int arguments to an Hour class' constructor to 0 through 23.
The answers to the above question mentioned throwing either Instantiation Exception or IllegalArgumentException, but were unclear about which is better style.
Also, when, if ever, is the overhead associated with the validation code justified?
It is correct only to throw an
IllegalArgumentException
.An
InstantiationException
is for a different purpose.An
InstantiationException
has to do with a reflection call failing to call a constructor, but anIllegalArgumentException
means that the constructor (or method) was called successfully, but the block of code determined that an argument was inappropriate.It is always best to have a little overhead to validate the arguments coming in to your constructor (and method). A program or class that isn't working properly is worse than a program that works properly and might be negligibly slower.