【发布时间】:2015-10-24 17:59:26
【问题描述】:
public class ExceptionExample3 {
public static void main(String[] args) {
MyExceptionExample3 obj = new MyExceptionExample3();
try {
obj.m2();
} catch (Exception e) {
System.out.println("main :" + e.getMessage());
}
System.out.println("main : resume here");
obj.m2(); // do not catch, terminate abnormally!
System.out.println("main : do not print this line ….");
}
}
class MyExceptionExample3 {
public void m1() {
System.out.println("m1 : print this line....");
// int x=5/0;
throw new RuntimeException("hello exception from m1()!");
// do not reach here!
}
public void m2() {
try {
m1();
} catch (Exception e) {
System.out.println("m2 :" + e.getMessage());
}
System.out.println("m2 : resume here");
m1(); // catch in main function
}
}
输出:
m1 : print this line....
m2 :hello exception from m1()!
m2 : resume here
m1 : print this line....
main :hello exception from m1()!
main : resume here
m1 : print this line....
m2 :hello exception from m1()!
m2 : resume here
m1 : print this line....
Exception in thread "main" java.lang.RuntimeException: hello exception
from m1()
这是在课堂上给出的一个关于异常的例子。我没有编写这个程序,但是我在跟踪这个异常example 程序时遇到了一些麻烦。我什至不确定为什么会抛出异常。如果有人可以请指导我完成这个程序,非常感谢。
【问题讨论】:
-
自己抛出异常并询问它们抛出的原因并不是一件好事。
-
throw new RuntimeException("hello exception from m1()!");这是你程序中的罪魁祸首。
-
这总是会从 m1 抛出异常,您可能需要添加一个条件,说明何时应该抛出异常
-
对不起,我应该更清楚。这是一个异常的课堂示例。我只是在跟踪程序和理解为什么需要异常/为什么抛出异常时遇到了麻烦。