Skip to content

Python 异常处理

TIP

异常处理让程序在遇到错误时能够优雅地恢复,而不是直接崩溃。

try-except

python
try:
    num = int(input("请输入数字: "))
    result = 10 / num
except ValueError:
    print("输入的不是有效数字")
except ZeroDivisionError:
    print("不能除以零")
except Exception as e:
    print(f"未知错误: {e}")
else:
    print("没有异常")
finally:
    print("无论如何都会执行")

自定义异常

python
class BusinessError(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message
        super().__init__(f"[{code}] {message}")

def withdraw(amount):
    if amount > balance:
        raise BusinessError(4001, "余额不足")