【发布时间】: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