嗨,我写了下面的代码。每次执行后,它都会以不同的顺序显示输出。
public class ExcetionInFinallyBlockDemo1 {
public static void main(String[] args) {
int a[] = new int[5];
try {
System.out.println("Accessing sixth element" + a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} finally {
System.out.println("finally block start");
try {
double divide = a[3] / 0;
System.out.println("Divide result:" + divide);
} catch (ArithmeticException e2) {
e2.printStackTrace();
}
System.out.println("Finall block end");
}
System.out.println("rest of the code");
}
}
第一次运行输出:
java.lang.ArrayIndexOutOfBoundsException: 5
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
java.lang.ArithmeticException: / by zero
finally block start
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)
Finall block end
rest of the code
第二次运行输出:
java.lang.ArrayIndexOutOfBoundsException: 5
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
finally block start
Finall block end
rest of the code
java.lang.ArithmeticException: / by zero
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)
第三次运行输出:
java.lang.ArrayIndexOutOfBoundsException: 5
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
java.lang.ArithmeticException: / by zero
at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)
finally block start
Finall block end
rest of the code
您能解释一下为什么每次打印顺序都不一样吗?
最佳答案
这是因为两个输出流System.out和System.err是独立缓冲的。
虽然我还没有完全理解为什么 - 我的第一个答案 - 刷新缓冲区 - 实际上没有帮助(正如鲍莫尔建议的那样),并且如果不使用自己的同步解决方案似乎不可能做到这一点。
一种简单的解决方法是仅使用一个缓冲区来处理 err 和 out,如下所示:
System.setErr(System.out);
关于java - 在finally block 中处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886752/