MySQL连接异常处理问题:try-except无法捕获异常致应用崩溃
问题分析与解决
你的核心问题一目了然:你把数据库连接代码mysql.connector.connect()放在了try代码块的外面,这就导致连接过程中抛出的异常完全没被你的except语句捕获,直接引发了应用崩溃。
看错误日志就能发现,连接时先触发了底层的TimeoutError,然后mysql connector把它包装成了InterfaceError——但这两个异常都发生在try块执行之前,你的except根本没机会处理它们。
修正后的代码方案
方案一:用try-finally手动管理连接
把连接调用移到try块内部,同时用finally确保连接一定会被关闭:
def check_server(server_address): con = None try: con = mysql.connector.connect( host=server_address, database='domicile_reports', user='xyz', password='xyz' ) if con.is_connected(): print(f'{server_address} Connected') except mysql.connector.Error as e: # 精准捕获MySQL相关异常,比泛用Exception更严谨 print(f"Can not connect to db. {e} Occured") finally: # 无论连接成功与否,都确保关闭连接释放资源 if con is not None and con.is_connected(): con.close() check_server('25.13.253.67')
方案二:用with语句自动管理连接(更推荐)
利用Python的上下文管理器自动处理连接关闭,代码更简洁安全:
def check_server(server_address): try: with mysql.connector.connect( host=server_address, database='domicile_reports', user='xyz', password='xyz' ) as con: if con.is_connected(): print(f'{server_address} Connected') except mysql.connector.Error as e: print(f"Can not connect to db. {e} Occured") check_server('25.13.253.67')
关键改进点说明
- 连接操作移入try块:这样连接过程中所有异常(超时、认证失败、网络错误等)都会被except捕获,不会直接崩溃应用
- 精准捕获异常:用
mysql.connector.Error替代Exception,避免捕获无关系统异常,让错误处理更精准 - 确保连接关闭:无论是手动finally还是自动with,都能防止连接资源泄漏,这在长期运行的应用中至关重要
内容的提问来源于stack exchange,提问作者Hamid Shah
相关产品推荐
相关产品推荐

