我有一个程序如下:
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 block 中返回时,异常没有被抛出到 main 方法?
最佳答案
当您的异常被抛出时,它将首先通过您的 finally
block 。
如果你的 finally
block 没有返回或抛出任何东西,那么原始异常将被传递。
另一方面,如果您的 finally
block 返回一个值,则根本不会再传播异常。
关于java - 尝试/最终没有捕获和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33098880/