我在做异常测试时,遇到一个不解的问题,网上找了资料也没见答案。在此贴出,希望各位大牛们能帮忙解惑。谢谢
问题描述:我在一个方法里面写了两个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]
为什么会出现这种情况,路过的请求解。谢谢
看了一下源代码,发现我说错了。 :oops:
正确的原因是:printStackTrace用的是System.err管道。所以,如果你把程序中的System.out都换成System.out就肯定没问题了。out和err是两个从系统中得到的不同句柄,至于为什么不是顺序的,就是并发的问题了。
应该是PrintStream的实现问题,当多个输出在很短时间内做请求的时候,其顺序是不保证的。你但不调试的的话,肯定是顺序的结果。
换成System.err :wink: 又手滑了