我周一参加了考试,因此正在做一些准备工作。现在我做了一个练习,看看如何在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(&#34; 6&#34;);没有执行?
非常感谢
答案 0 :(得分:0)
首先,您可以运行代码来查看结果。
当在方法中捕获execption时,该方法是否继续正常?
是。我的意思是它会继续走得更远。例如,如果doA()抛出异常,则run()方法不打印&#39; 3&#39;。 (但它会打印&#39; 5&#39;总是因为最后
然后只执行finally块,然后方法中断。所以在run()中有System.out.print(&#34; 6&#34;);没有执行?
最后块总是在try块之后执行。是例外与否。