java - 尝试/最终没有捕获和返回值

标签 java exception-handling try-catch-finally

我有一个程序如下:

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/

相关文章:

java - instanceof 是否适用于子类异常?

c++ - C++ 最快 `finally`

java - 单元测试最终在 Java 6 中阻塞

java - 似乎无法将自定义对象写入 Firebase 数据库?

java - 如何枚举哈希表的键和值?

java - 设置每行的 Edittext 背景

python - 为什么不打印异常?

java - 充气机和循环无法正常工作

c# - 找到最内层异常的正确方法?

java - try-catch-finally 后返回