【发布时间】:2016-01-10 23:31:36
【问题描述】:
我有一个程序如下:
public class Main {
public static void main(String[] args)throws Exception
{
int res = test();
System.out.println("after call , res = " + res) ;
}
public static int test()throws Exception
{
try
{
return 10/0;
}
finally
{
System.out.println("finally") ;
}
}
}
上面的程序运行后,在控制台看到如下结果:
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.test(Main.java:17)
at Main.main(Main.java:7)
这种行为是正常的,因为 main 方法抛出了异常。
然后我将代码更改如下:
public class Main {
public static void main(String[] args)throws Exception
{
int res = test();
System.out.println("after call , res = " + res) ;
}
public static int test()throws Exception
{
try
{
return 10/0;
}
finally
{
System.out.println("finally") ;
return 20;
}
}
}
在上面的程序运行时,我在控制台中看到了以下结果:
finally
after call , res = 20
我的问题与第二种格式有关。为什么在 finally 块中返回时,异常没有被抛出到 main 方法?
【问题讨论】:
-
众所周知,不要在
finally块中使用return,它不适合这样的事情。如果这样做,异常将被丢弃。
标签: java exception-handling try-catch-finally