【问题标题】:Why is Output different every time? try catch finally exception code为什么每次输出都不一样? try catch finally 异常代码
【发布时间】:2015-08-11 08:05:36
【问题描述】:
class TestExceptions {

    public static void main(String[] args) throws Exception {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            throw new RuntimeException();
        } finally {
            System.out.println("finally");
        }
    }
}

以下是我尝试在 Eclipse 中多次运行代码时的输出。到目前为止,我相信每当 try/catch 块中的最后一行代码即将被执行(可能是返回或抛出新的 Exception() 类型的 stmt),finally 块都会被执行,但这里的输出不同每次?谁能澄清我的假设是对还是错?

try
catch
Exception in thread "main" finally
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)


Exception in thread "main" try
catch
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)
finally

【问题讨论】:

标签: java exception


【解决方案1】:

这显然是因为 Eclipse 正在打印 error streamoutput stream 而没有在控制台中正确同步。很多人都因此而看到了问题。

在命令提示符下执行程序,每次都会看到正确的输出。

【讨论】:

  • 是的,当我从命令提示符多次运行它时,我得到了以下输出。 try catch finally Exception in thread "main" java.lang.RuntimeException at TestExceptions.main(TestExceptions.java:9) Eclipse ,错误流和输出流是异步的,这是我今天学到的新东西。但是他们仍在访问同一个控制台,甚至命令提示符都在访问单个输出控制台。为什么会有如此巨大的差异?
【解决方案2】:

在同意@Codebender 的同时,您可以替换所有 thows 异常并用 printStackTrace();然后异常和 out 将在 syn 中打印。 例如:

 public static void main(String[] args) throws Exception {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }
    }
}

【讨论】:

  • printStackTrace 也会打印到错误流。所以什么都不应该改变。我建议使用System.err 而不是System.out 以获得一致的输出。
  • 但在这种情况下它将使用相同的胎面“主”胎面。所以输出将是有序的。
猜你喜欢
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 2010-09-12
  • 2011-03-28
相关资源
最近更新 更多