【发布时间】:2018-07-06 12:33:05
【问题描述】:
我星期一有考试,因此正在做一些准备工作。现在我做了一个练习,看看java是如何处理异常的。
我有以下代码要分析:
public class ExceptionsExercise {
private int x;
private class E1 extends Exception {
E1() {
super("exception E1");
}
}
private class E2 extends Exception {
E2() {
super("exception E2");
}
}
private class E3 extends Exception {
E3() {
super("exception E3");
}
}
public void run() throws E1, E3 {
try {
doA();
System.out.print("3 ");
} catch (E2 e) {
System.out.print("4 ");
} finally {
System.out.print("5 ");
}
System.out.print("6 ");
}
public void doA() throws E1, E2, E3 {
if (x == 1) {
throw new E1();
} else if (x == 2) {
throw new E2();
} else {
doB();
System.out.print("7 ");
}
}
public void doB() throws E3 {
if (x == 3) {
System.out.print("8 ");
throw new E3();
} else {
System.out.print("9 ");
}
}
public static void main(String[] args) {
Main thisInstance = new Main();
for (int i = 0; i < 4; i++) {
thisInstance.x = i;
System.out.println("");
System.out.print("x = " + i + " ");
try {
thisInstance.run();
} catch (E1 e) {
System.out.println("0");
} catch (E3 e) {
}
System.out.println("2 ");
}
}
}
现在的问题是输出是什么。但是我遇到了一些问题。例如,当一个方法中捕获了一个execption时,该方法是否继续正常?就像在捕获异常 e2 后的方法 run() 中一样。
相反的情况是方法没有捕获异常。然后只是执行 finally 块,然后方法中断。这样在 run() 中 System.out.print("6");不执行?
非常感谢
【问题讨论】:
-
现在的问题是输出是什么:编译并运行代码,你就会看到。
-
我知道输出,那不是我的问题。我的问题是,我不知道 java 对这两种情况有何反应。
-
如何分析输出并得出结论?如何在代码中添加 println 语句以了解更多信息?如何使用调试器逐行执行代码。这些都是你应该能够自己做的简单的事情。或者您可以阅读任何有关异常的书籍或教程。 docs.oracle.com/javase/tutorial/essential/exceptions
-
您确实“知道 Java 如何应对这两种情况”。你的程序的输出告诉你。不清楚你在问什么,
-
Java 语言规范The try statement
标签: java exception exception-handling try-catch