"""第 08 章 錯誤與例外。"""

# read-traceback
from traceback import extract_tb


def parse_seats(text):
    return int(text)


try:
    parse_seats("三")
except ValueError as error:
    location = extract_tb(error.__traceback__)[-1]
    print(type(error).__name__)
    print("出錯函式", location.name)

# validate-seats
for raw in ("4", "abc", "-1"):
    try:
        seats = int(raw)
    except ValueError:
        print("請輸入整數")
    else:
        if seats < 0:
            print("座位數不可為負")
        else:
            print(f"登記 {seats} 席")

# reject-invalid-range
def require_positive_seats(seats):
    if seats <= 0:
        raise ValueError("至少要有一個座位")
    return seats


try:
    require_positive_seats(0)
except ValueError as error:
    print(error)

# error-practice
samples = (" 12 ", "十二")
quantities = (10, 11)
# 組合型別轉換、例外處理與範圍驗證。
print("分開處理轉換失敗和超出範圍。")

# error-solutions
for text in (" 12 ", "十二"):
    try:
        value = int(text)
    except ValueError:
        print("格式不符")
    else:
        print(value)


def validate_quantity(quantity):
    if not 1 <= quantity <= 10:
        raise ValueError("數量須介於 1 到 10")
    return quantity


for quantity in (10, 11):
    try:
        print(validate_quantity(quantity))
    except ValueError as error:
        print(error)
