# ===== CodeLab: Python 异常处理与调试 =====
# 来源: https://aoerliang.dpdns.org/articles/python-errors
# 以下代码片段按文章出现顺序拼接, 共 6 段

# ----- 片段 1 (python) -----
try:
    num = int(input("请输入数字: "))
    print(10 / num)
except ValueError:
    print("输入的不是数字!")
except ZeroDivisionError:
    print("不能除以零!")

# ----- 片段 2 (python) -----
try:
    data = {"name": "Ada"}.get("age") + 1
except TypeError as e:
    print("出错了:", e)

# ----- 片段 3 (python) -----
try:
    f = open("data.txt", encoding="utf-8")
    content = f.read()
except FileNotFoundError:
    print("文件不存在")
else:
    print(f"读取成功,共 {len(content)} 字符")
finally:
    print("清理:关闭文件")

# ----- 片段 4 (python) -----
def withdraw(balance, amount):
    if amount < 0:
        raise ValueError("取款金额不能为负")
    if amount > balance:
        raise ValueError("余额不足!")
    return balance - amount

try:
    withdraw(100, 200)
except ValueError as e:
    print("取款失败:", e)

# ----- 片段 5 (python) -----
class InsufficientFundsError(Exception):
    """余额不足异常"""
    pass

def pay(balance, price):
    if price > balance:
        raise InsufficientFundsError(
            f"需要 {price},余额只有 {balance}"
        )
    return balance - price

try:
    pay(50, 100)
except InsufficientFundsError as e:
    print("支付失败:", e)

# ----- 片段 6 (python) -----
import logging
import traceback

logging.basicConfig(level=logging.DEBUG)

def process(items):
    logging.debug(f"收到 {len(items)} 条数据")   # 过程打点
    result = []
    for i, item in enumerate(items):
        try:
            result.append(item * 2)
        except TypeError:
            logging.warning(f"第 {i} 条数据异常: {item!r}")
    return result

process([1, "x", 3])

# 打印完整堆栈
try:
    1 / 0
except ZeroDivisionError:
    traceback.print_exc()
