方法
49、检查参数的有效性
每次编写方法或构造函数时,都应该考虑参数存在哪些限制,并在文档中记录下来,然后在方法的开头显式地检查。
如果没有在方法开头就验证参数,可能会违反故障原子性。因为方法可能会在执行过程中出现让人困惑的异常而失败,或者计算出错误的结果然后返回,甚至可能埋藏隐患,导致将来在不确定的某处代码产生错误。
对于公共方法和受保护的方法,使用@throws 标签记录违反参数限制会引发的异常,例如 IllegalArgumentException、IndexOutOfBoundsException 或 NullPointerException。见下面例子:
[code]/*** Returns a BigInteger whose value is (this mod m). This method* differs from the remainder method in that it always returns a* non-negative BigInteger.**@param m the modulus, which must be positive* @return this mod m* @throws ArithmeticException if m is less than or equal to 0*/public BigInteger mod(BigInteger m) { if (m.signum() |