# G4-08 课后练习 —— 异常进阶
> **GESP等级：四级 | 考级考点：GESP Python 四级**

**姓名：__________  日期：__________**

---

> 面向7-10岁少儿 | G4 编程高手

---

## 一、填空题（回顾概念）

**题目1：** `try/except/else/finally` 结构中，____块在没有发生异常时执行，____块不管有没有异常都会执行。

**题目2：** `raise` 关键字的作用是____。例如 `raise ValueError("非法输入")` 会主动抛出一个____类型的异常。

---

## 二、代码补全（补写代码）

**题目3：** 编写程序，让用户输入年龄，要求年龄在0-150之间。如果不在范围内，用 `raise` 主动抛出异常。补全代码。

```python
try:
    age = int(input("请输入年龄："))

    if age < 0 ____ age > 150:
        ____ ValueError(f"年龄{age}不在有效范围0-150内！")

    print(f"你的年龄是：{age}岁")

____ ValueError as e:
    print(f"输入错误：{e}")

____:
    print("年龄输入有效！")

____:
    print("程序执行完毕。")
```

**题目4：** 读取文件时，分别处理文件不存在、权限不足和其他错误。补全代码。

```python
try:
    ____ open("data.txt", "r") as f:
        content = f.read()
        print(content)
____ FileNotFoundError:
    print("文件不存在，请检查文件名！")
____ PermissionError:
    print("没有权限读取该文件！")
____ Exception ____ e:
    print(f"发生了其他错误：{e}")
____:
    print("文件读取成功！")
____:
    print("文件操作结束。")
```

---

## 三、创作题（动手编程）

**题目5：** 编写"自定义异常测温仪"程序。
- 定义一个自定义异常类 `TemperatureError`，继承自 `Exception`
- 编写函数 `check_temperature(temp)`，当温度：
  - 低于 -50℃ 或高于 50℃：抛出 `TemperatureError("温度超出测量范围！")`
  - 低于 0℃：打印"🥶 天冷，注意保暖！"
  - 高于 35℃：打印"🥵 天热，注意防暑！"
  - 正常范围：打印"🌤️ 温度适宜！"
- 主程序循环让用户输入温度，直到输入"quit"退出
- 使用完整的 `try/except/else/finally` 结构处理

请写出完整代码。

<details>
<summary>参考答案</summary>

**题目1：** else，finally

**题目2：** 主动抛出异常，ValueError

**题目3：**
```python
try:
    age = int(input("请输入年龄："))

    if age < 0 or age > 150:
        raise ValueError(f"年龄{age}不在有效范围0-150内！")

    print(f"你的年龄是：{age}岁")

except ValueError as e:
    print(f"输入错误：{e}")

else:
    print("年龄输入有效！")

finally:
    print("程序执行完毕。")
```

**题目4：**
```python
try:
    with open("data.txt", "r") as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("文件不存在，请检查文件名！")
except PermissionError:
    print("没有权限读取该文件！")
except Exception as e:
    print(f"发生了其他错误：{e}")
else:
    print("文件读取成功！")
finally:
    print("文件操作结束。")
```

**题目5：**
```python
# 自定义异常类
class TemperatureError(Exception):
    pass

def check_temperature(temp):
    if temp < -50 or temp > 50:
        raise TemperatureError(f"温度{temp}℃超出测量范围（-50℃~50℃）！")
    elif temp < 0:
        print("🥶 天冷，注意保暖！")
    elif temp > 35:
        print("🥵 天热，注意防暑！")
    else:
        print("🌤️ 温度适宜！")

# 主程序
print("===== 智能测温仪 =====")
print("输入温度值，输入 'quit' 退出")

while True:
    user_input = input("\n请输入温度：")

    if user_input.lower() == "quit":
        print("测温仪已关闭。")
        break

    try:
        temp = float(user_input)
        check_temperature(temp)
    except ValueError:
        print("输入无效！请输入数字温度值。")
    except TemperatureError as e:
        print(f"⚠️ 异常报警：{e}")
    else:
        print("✅ 本次测温已完成。")
    finally:
        print("---")
```
</details>


---

**自我评价：** □ 全都会了  □ 大部分会了  □ 还要再练练
