【问题标题】:Different output when Exception Handling Java code is run multiple times多次运行异常处理 Java 代码时的不同输出
【发布时间】:2014-12-19 12:14:49
【问题描述】:

我知道在这个网站上提出了很多关于 try-catch-finally 块的问题。但我有不同的疑问。当下面的代码多次运行时,我得到不同的输出。

我有一个非常简单的类如下:

实践.java

public class Practice {
    public static void main(String []args) {
         System.out.println(getInteger());
    }

    public static int getInteger() {
       try {
           System.out.println("Try");
           throwException();
           return 1;
       } catch(Exception e) {
           System.out.println("Catch Exception");
           e.printStackTrace();
           return 2;
       } finally {
            System.out.println("Finally");
      }
    }

   private static void throwException() throws Exception {
       throw new Exception("my exception");
   }
}

我第一次运行上面的代码时的输出如下:

Try
Catch Exception
Finally
2
java.lang.Exception: my exception
    at exceptionHandling.Practice.throwException(Practice.java:22)
    at exceptionHandling.Practice.getInteger(Practice.java:10)
    at exceptionHandling.Practice.main(Practice.java:4)

当我再次运行代码时,不同的输出如下所示:

Try
Catch Exception
java.lang.Exception: my exception
    at exceptionHandling.Practice.throwException(Practice.java:22)
    at exceptionHandling.Practice.getInteger(Practice.java:10)
    at exceptionHandling.Practice.main(Practice.java:4)
Finally
2

有人可以解释一下这样的输出吗?

【问题讨论】:

    标签: java exception-handling try-catch


    【解决方案1】:

    您使用不同的文件句柄。您的输出将发送到 System.oute.printStackTrace(); 写入 System.err,这将在不同时间刷新。

    【讨论】:

    • 谢谢。我不知道这个。我想找到执行顺序
    猜你喜欢
    • 2017-10-20
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多