我目前正在学习 Java 的入门类(class),这是关于 try-catch 方法的。当我输入这个时,我的 System.out.println
语句不断重复。这是我的代码:
public static double exp(double b, int c) {
if (c == 0) {
return 1;
}
// c > 0
if (c % 2 == 0) {
return exp(b*b, c / 2);
}
if (c<0){
try{
throw new ArithmeticException();
}
catch (ArithmeticException e) {
System.out.println("yadonegoofed");
}
}
// c is odd and > 0
return b * exp(b, c-1);
}
最佳答案
if (c<0){
try{
throw new ArithmeticException();
}
catch (ArithmeticException e) {
System.out.println("yadonegoofed");
}
}
// c is odd and > 0
return b * exp(b, c-1);
您的评论 c 很奇怪并且 > 0
是不正确的——您实际上从未终止异常函数。你扔了,你马上接住了,然后继续执行递归函数。最终,当你点击 wraparound 时,它又会是一个正数,错误就不会发生了。 (还有大约 20 亿次迭代——别等了。)
我不会在这里使用异常——您只需要终止递归。我会在 检查 0
之前检查负输入,并在那里抛出异常,然后在调用者中捕获异常。
在伪代码中:
exp(double b, int c) {
if (c < 0)
throw new Exception("C cannot be negative");
} else if (c % 2 == 0) {
return exp(b*b, c / 2);
} else {
/* and so forth */
}
}
关于java - 关于try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10133905/