我是编程的新手,我正在学习Java作为我的第一个oo语言,通过David J. Eck编写的Java编程简介和卡住的论坛帖子.
我的问题可以被认为是Java Class Constructor Parameters with range limits的后续,它涉及将Hour类的构造函数的int参数限制为0到23.
上述问题的答案提到抛出Instantiation Exception或IllegalArgumentException,但不清楚哪个是更好的样式.
此外,如果有的话,与验证代码相关的开销是否合理?
解决方法:
抛出IllegalArgumentException
只是正确的.
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
InstantiationException
用于不同的目的.
Thrown when an application tries to create an instance of a class using the newInstance method in class
Class
, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:
the class object represents an abstract class, an interface, an array class, a primitive type, or
void
the class has no nullary constructor
InstantiationException与无法调用构造函数的反射调用有关,但是IllegalArgumentException意味着成功调用了构造函数(或方法),但代码块确定参数不合适.
最好有一点开销来验证进入构造函数(和方法)的参数.一个不能正常工作的程序或类比一个正常工作的程序更糟糕,并且可能会慢得忽视.