每次编写方法或构造函数时,都应该考虑参数存在哪些限制,并在文档中记载下来,然后在方法的开头显式地检查。
如果没有在方法开头就验证参数,大概会违反故障原子性。因为方法大概会在执行过程中出现让人困惑的非常而失败,或者计算出错误的结果然后返回,甚至大概埋藏隐患,导致将来在不确定的某处代码产生错误。
对于公共方法和受掩护的方法,使用@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()