【发布时间】:2013-08-27 08:44:35
【问题描述】:
public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
try {
a[0] = 4;
if (i <= 0) {
int k = j / i;
} else {
System.out.println(j / i);
}
} catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
void k() {
int[] a = new int[2];
{
try {
a[4] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range");
}
}
}
}
public class Nested {
public static void main(String[] args) {
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}
}
输出:
-2
Executing finally block in code
Wrong valuejava.lang.ArithmeticException: / by zero
Executing finally block in code
out of range
out of range
每当我执行下面代码中编写的finally{} 块时,它都会被执行两次。不知道为什么会这样。我只想运行 finally 块一次。
有没有办法在一个方法中抛出多个异常?
【问题讨论】:
-
因为你调用了两次,不是吗?
-
不用在构造函数中有逻辑并有这种“问题”,你可以将逻辑移动到一个方法中,这样就很简单了...... 2 方法调用 = 2
try{}catch{}finally{}块跨度>
标签: java exception-handling try-catch-finally