In this code will someVar be set even if the catch block is executed and the second Exception is thrown?

public void someFunction() throws Exception {
    try {
        //CODE HERE
    } catch (Exception e) {
        Log.e(TAG, "", e);
        throw new Exception(e);
    } finally {
        this.someVar= true;
    }
}

推荐答案

Yes, the finally blocks always runs... except when:

  • The thread running the try-catch-finally block is killed or interrupted
  • You use System.exit(0);
  • The underlying VM is destroyed in some other way
  • The underlying hardware is unusable in some way

Additionally, if a method in your finally block throws an uncaught exception, then nothing after that will be executed (i.e. the exception will be thrown as it would in any other code). A very common case where this happens is java.sql.Connection.close().

As an aside, I am guessing that the code sample you have used is merely an example, but be careful of putting actual logic inside a finally block. The finally block is intended for resource clean-up (closing DB connections, releasing file handles etc), not for must-run logic. If it must-run do it before the try-catch block, away from something that could throw an exception, as your intention is almost certainly functionally the same.

Java相关问答推荐

Java Streams在矩阵遍历中的性能影响

CSS应用于一个端点,但不应用于Thymeleaf中的另一个端点

RxJava PublishSubject缓冲区元素超时

如何以干净的方式访问深度嵌套的对象S属性?

对某一Hyroby控制器禁用@cacheable

将不受支持的时区UT重写为UTC是否节省?

如何获得执行人?

为什么我的在一个范围内寻找素数的程序不能像S所期望的那样工作

Mapstruct不能正确/完全映射属性

有没有办法让扩展变得多态?

使用存储在字符串变量中的路径目录打开.pdf文件

为什么Collectors.toList()不能保证易变性

使用While循环打印素数,无法正常工作

Java创建带有扩展通配符的抽象处理器

JavaFX:无论何时显示应用程序,如何更改组件/ node 位置?

为什么相同的数据条码在视觉上看起来不同?

为什么使用lo索引来解决二进制搜索问题不同于使用hi索引?

由于版本不匹配,从Java 8迁移到Java 17和Spring 6 JUnit4失败

Hibernate 命名策略导致 Java Spring Boot 应用程序中出现未知列错误

如何在Java中调用对象上预定义的接口方法列表?