【发布时间】:2017-01-10 16:34:50
【问题描述】:
我试图了解为什么要抛出某些异常。我选择扔哪一个有什么关系?
例如
//simple division method - a/b
public static double divide(double a, double b){
if(b == 0)
throw new IllegalArgumentException("b = 0");
return a/b;
}
对
//simple division method - a/b
public static double divide(double a, double b){
if(b == 0)
throw new IllegalArithmeticException("b = 0");
return a/b;
}
(如果代码中有错误,我深表歉意 - 我很快就把它放在一起。我实际上对方法本身并不感兴趣。)
我选择哪个例外有关系吗?它似乎可以是任何东西 - 即使我使用了 arrayIndexOutOfBoundsException,它仍然会停止程序并打印我想要它打印的内容。
感谢您的帮助。
【问题讨论】:
-
有人使用您的代码并获得
ArrayIndexOutOfBoundsException。他们会猜到问题是什么? -
明白了,但是在 IllegalArithmeticException 和 IllegalArgumentException 的情况下,除了名称之外还有其他理由选择一个吗?
标签: java exception exception-handling throw