我在做异常测试时,遇到一个不解的问题,网上找了资料也没见答案。在此贴出,希望各位大牛们能帮忙解惑。谢谢
问题描述:我在一个方法里面写了两个try,并在相应的catch语句后面都有输出语句用来判断方法是否因异常而终止。这样问题就来了,每次运行,输出的结果都不一样,有点随机的感觉。很是疑惑,为什么一段代码每次执行的输出结果不一样????
代码如下
[code="java"]
public class Test {
public static void main(String[] args) {
try {
Object o = new String();
Integer i = (Integer)o;
}catch(Exception e) {
e.printStackTrace();
}
System.out.println("the code after ClassCastException_try");
try {
int i = 9/0;
}catch(Exception e) {
e.printStackTrace();
}
System.out.println("the code after ArithmeticException_try");
//int j = 8/0;
String str = new String();
str = "hello world";
System.out.println(str);
}
}
[/code]
输出结果有:
[code="java"]
(1):
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at Test.main(Test.java:6)
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:13)
-----the code after ClassCastException_try
-----the code after ArithmeticException_try
-----hello world
(2):
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at Test.main(Test.java:6)
-----the code after ClassCastException_try
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:13)
-----the code after ArithmeticException_try
-----hello world
(3)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
-----the code after ClassCastException_try
-----the code after ArithmeticException_try
-----hello world
at Test.main(Test.java:6)
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:13)
(4)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at Test.main(Test.java:6)
java.lang.ArithmeticException: / by zero
-----the code after ClassCastException_try at Test.main(Test.java:13)
-----the code after ArithmeticException_try
-----hello world
[/code]
为什么会出现这种情况,路过的请求解。谢谢