try/finally without catch and return value
2022-09-01 14:33:03
我有一个程序如下:
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
我的问题与第二种格式有关。为什么在返回时最终阻塞,异常没有抛出到main方法?