finally_clause_and_return_clause_in_java

本文详细解析了 Java 中 try-catch-finally 结构中 finally 块的执行流程,包括正常完成与异常情况下的行为,并介绍了 return 语句在方法调用中的控制转移过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

             The only time finally won't be called is if you call System.exit() or if the JVM crashes first.


A try statement with a finally block is executed by first executing thetry block. Then there is a choice:

  • If execution of the try block completes normally, [...]
  • If execution of the try block completes abruptly because of a throw of a value V, [...]
  • If execution of the try block completes abruptly for any other reasonR, then thefinally block is executed. Then there is a choice:
    • If the finally block completes normally, then the try statement completes abruptly for reasonR.
    • If the finally block completes abruptly for reason S, then thetry statement completes abruptly for reasonS (and reasonR is discarded).

ReturnStatement:
     return Expression(opt) ;

A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.

A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of theExpression becomes the value of the method invocation.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are anytry statements within the method or constructor whosetry blocks contain thereturn statement, then any finally clauses of thosetry statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of afinally clause can disrupt the transfer of control initiated by areturn statement.


Ref: 

Does finally always execute in Java?

14.20.2 Execution of try-catch-finally se5                 se7

14.17 The return Statement  se5               se7


为了解决上述问题,以下是修改后的代码: ```python import hashlib import streamlit as st import sqlite3 import pandas as pd from datetime import datetime, timedelta, time as datetime_time import threading from queue import Queue # 数据库配置 DB_PATH = "enterprise.db" MAIN_TABLE = "生产结果表" class ThreadSafeDB: """线程安全的数据库连接池""" _instance = None _lock = threading.Lock() def __new__(cls): with cls._lock: if not cls._instance: cls._instance = super().__new__(cls) cls._instance._connection_pool = Queue(maxsize=5) for _ in range(5): conn = sqlite3.connect( DB_PATH, check_same_thread=False, timeout=10 ) cls._instance._connection_pool.put(conn) return cls._instance def get_conn(self): return self._connection_pool.get() def return_conn(self, conn): self._connection_pool.put(conn) def get_db_connection(): """获取数据库连接(线程安全)""" db_pool = ThreadSafeDB() return db_pool.get_conn() @st.cache_data(ttl=3600, show_spinner=False) def fetch_production_data(params): """获取生产数据(线程安全版本)""" try: conn = get_db_connection() try: where_clause, args = build_base_query(params) base_query = f"SELECT * FROM `{MAIN_TABLE}`" if where_clause: base_query += f" WHERE {where_clause}" df = pd.read_sql(base_query, conn, params=args) return df finally: ThreadSafeDB().return_conn(conn) except Exception as e: st.error(f"数据库查询失败: {str(e)}") return pd.DataFrame() def build_base_query(params): """构建基础查询条件""" conditions = [] args = [] if params.get('unit'): conditions.append("机组名 = ?") args.append(params['unit']) if params.get('start_time'): conditions.append("生产开始时间 >= ?") args
03-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值