public-image-mirror 拉取镜像时如何选择 sha256 摘要、固定版本 tag 与 latest 引用方式
2026/9/15 22:24:06
Python 的异常(Exceptions)是程序运行时发生的错误信号,用于处理程序中的非正常情况。通过异常机制,你可以优雅地捕获和处理错误,避免程序崩溃。
表格
| 异常类型 | 说明 | 示例 |
|---|---|---|
SyntaxError | 语法错误(通常在解析阶段就报错,不属于运行时异常) | print("hello"(缺少右括号) |
NameError | 使用未定义的变量 | print(x)(x 未定义) |
TypeError | 类型不匹配 | "a" + 1 |
ValueError | 值正确但类型不合适 | int("abc") |
IndexError | 序列索引超出范围 | [1,2][5] |
KeyError | 字典中找不到指定键 | d = {}; d['missing'] |
ZeroDivisionError | 除零错误 | 1 / 0 |
FileNotFoundError | 文件未找到 | open('not_exist.txt') |
AttributeError | 对象没有该属性 | "str".append() |
ImportError | 导入模块失败 | import non_existent_module |
所有异常都继承自
BaseException,但用户自定义异常通常继承自Exception。
try...except基本语法:
try: # 可能引发异常的代码 result = 10 / 0 except ZeroDivisionError: # 处理特定异常 print("不能除以零!")try: num = int(input("请输入一个数字: ")) result = 100 / num except ValueError: print("请输入有效的数字!") except ZeroDivisionError: print("不能输入零!") except Exception as e: # 处理所有其他异常 print(f"发生了未知错误: {e}")def divide_numbers(x, y): try: result = x / y except ZeroDivisionError as e: print(f"除数不能为零: {e}") result = None except TypeError as e: print(f"类型错误: {e}") result = None else: # 只有在没有异常发生时执行 print("计算成功!") finally: # 无论是否发生异常都会执行 print("执行结束") return result # 测试 print(divide_numbers(10, 2)) # 正常 print(divide_numbers(10, 0)) # 除以零 print(divide_numbers(10, "2")) # 类型错误# 创建自定义异常 class MyCustomError(Exception): """自定义异常类""" def __init__(self, message, error_code): super().__init__(message) self.error_code = error_code def __str__(self): return f"{self.args[0]} (错误代码: {self.error_code})" # 使用自定义异常 def validate_age(age): if age < 0: raise MyCustomError("年龄不能为负数", 1001) elif age > 150: raise MyCustomError("年龄超出合理范围", 1002) return True # 测试自定义异常 try: validate_age(-5) except MyCustomError as e: print(f"自定义错误: {e}, 代码: {e.error_code}")raisedef divide(a, b): if b == 0: raise ValueError("除数不能为零!") return a / b # 调用 try: divide(10, 0) except ValueError as e: print(e) # 输出:除数不能为零!# ❌ 不推荐 try: ... except: pass这会隐藏所有错误,包括系统退出(如KeyboardInterrupt)。Exception(除非必要)。logging模块记录错误信息。