wuzhihui001 2011-10-06 12:54
浏览 581
已采纳

一个方法里面多个try,问题求解,谢谢

我在做异常测试时,遇到一个不解的问题,网上找了资料也没见答案。在此贴出,希望各位大牛们能帮忙解惑。谢谢

问题描述:我在一个方法里面写了两个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]

为什么会出现这种情况,路过的请求解。谢谢

  • 写回答

3条回答 默认 最新

  • hareamao 2011-10-06 18:38
    关注

    看了一下源代码,发现我说错了。 :oops:

    正确的原因是:printStackTrace用的是System.err管道。所以,如果你把程序中的System.out都换成System.out就肯定没问题了。out和err是两个从系统中得到的不同句柄,至于为什么不是顺序的,就是并发的问题了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题