我正在尝试编写一个程序来将任意数字的值等同于任何权力,我想为小于零的指数实现异常处理,这是我成功完成的,同时还为异常处理该值太大而无法输出,即无穷大。Infinity的Java异常处理
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
继承人的测试类:
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
继承人测试的输出:
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
我的问题是
其中包含功能电源我的继承人功率等级我怎样才能通过ArithmeticException处理某些事情而得到“结果无穷大”来说别的东西沿着“浮点溢出”的线?
在此先感谢。
目前还不清楚你在问什么。如果结果是无限的,你想抛出异常吗?你想知道如何检查结果是无限的吗? – Radiodef 2014-12-07 22:40:27
结果无限时抛出异常 – 2014-12-07 22:40:58
清楚地知道如何抛出异常。也许你可以编辑你的问题来澄清你遇到的问题。 – Radiodef 2014-12-07 22:41:48