Python的异常处理

本文最后更新于 2026年5月1日

未完待续

1.错误、异常和断言

  • 错误 语法错误,语法检查都过不去
  • 异常 程序语法是正确的,运行到一些地方,也可能会出现错误,运行时检测到的错误就称之为异常
  • 断言 用于判断一个表达式,在表达式条件为false的时候,触发异常

2.异常处理

java中的异常处理包含:try => catch => finally几个步骤,python中的异常处理则是:try => except => else => finally

2.1 try/except

except捕获异常

try:
    i = 1 / 0
    print("正常执行")
except:
    print("发生异常了") #发生异常了

2.2 try/except/else

try内没有异常,else块内代码才会执行,else必须放在所有except的后面

__doc__ 是 Python 中每个对象都可能具有的属性,用于存储该对象的文档字符串

try:
    result = 3 / 0
except ZeroDivisionError as e:
    # 打印:异常名 + 异常描述
    print(f"1.异常名:{type(e).__name__},异常信息:{e.__doc__}")
except (RuntimeError, TypeError, NameError) as e:
    print(f"2.异常名:{type(e).__name__},异常信息:{e}")
except:
    print("Unexpected error")
else:
    # try内无异常时执行的固定逻辑
    print("try内无异常时执行的固定逻辑")
    print(result)
1.异常名:ZeroDivisionError,异常信息:Second argument to a division or modulo operation was zero.

如果改为result = 3 / 1,则输出

try内无异常时执行的固定逻辑
3.0

2.3 try/except/finally

无论try内是否出现异常,异常是否被捕获,finally块内语句都会执行

try:
    result = 3 / 0
except ZeroDivisionError as e:
    print(f"异常名:{type(e).__name__},异常信息:{e.__doc__}")
else:
    print(result)
finally:
    print("finally")
异常名:ZeroDivisionError,异常信息:Second argument to a division or modulo operation was zero.
finally

如果改为result = 3 / 1,则输出

3.0
finally

⚠️ finally一定会执行,所以finally中要谨慎访问可能因异常导致不存在的变量

try:
   result = 3 / 0
except ZeroDivisionError as e:
   print(f"异常名:{type(e).__name__},异常信息:{e.__doc__}")
else:
   print(result)
finally:
   print(result) # ❌ NameError: name 'result' is not defined
   print("finally")

2.4 总结

  • try 执行可能产生异常的代码
  • except 发生异常时执行
  • else 没有发生异常时执行
  • finally 有没有异常都会执行

3.异常的产生

3.1 raise抛出

def int_add(x, y):
    if isinstance(x, int) and isinstance(y, int):
        return x + y
    else:
        raise TypeError("参数类型错误")

print(int_add(1, 2))  # 3
print(int_add("1", "2")) # TypeError: 参数类型错误

3.2 assert断言

语法:assert [表达式], "异常信息",表达式一旦我们的断言的预期不符,自动抛出AssertionError

def divide(a, b):
    assert b != 0, "断言触发,除数不能为0"
    return a / b

print(divide(10, 2))  # 5.0
print(divide(10, 0)) # AssertionError: 断言触发,除数不能为0

assert本质上就是简化版的raise,多用于日常开发测试,在生产环境中,应当使用raise,可以通过执行带参数的python -O ***.py命令,屏蔽掉代码中全部的assert语句,直接跳过,不判断不抛异常

4.自定义异常

继承Exception自定义异常,自定义一个属性value

__init__(self, value)会覆盖掉父类Exception的__init__()

class MyError(Exception):
    """我是异常doc"""
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

if __name__ == '__main__':
    try:
        raise MyError('fuck')
    except MyError as e:
        print(f"触发自定义异常:{type(e).__name__},异常描述:{e.__doc__},异常信息:{e.value}")
触发自定义异常:MyError,异常描述:我是异常doc,异常信息:fuck

"如果文章对您有帮助,可以请作者喝杯咖啡吗?"

微信二维码

微信支付

支付宝二维码

支付宝


Python的异常处理
https://blog.liuzijian.com/post/2026/02/01/python-exception/
作者
Liu Zijian
发布于
2026年2月1日
更新于
2026年5月1日
许可协议