main.py
Costs 1 credit
加载编辑器中...
输出 Output执行成功
# 运行代码后,输出将显示在这里 # 按 Ctrl+Enter 快速运行
Terminal (Simulated)Install commands are simulated only, no real network requests
$
Step 1: 捕获异常
try/except 的核心价值是:程序遇错不崩,改为可控反馈。
底层逻辑:
匹配成功后,异常被处理,程序继续向下执行。
try 块抛出异常后,解释器会跳转到匹配的 except 分支。匹配成功后,异常被处理,程序继续向下执行。
你的任务:
- 尝试将字符串 "abc" 转换为整数
- 使用 try/except 捕获 ValueError
- 打印友好的错误信息
正常情况下 int("abc") 会报错,但我们要优雅地处理它。
Self-Check List
- 使用 try/except
- 捕获 ValueError
Transfer Template
try:
num = int("abc")After completing this step, you should be able to independently explain and reproduce this concept, then apply it to similar problems.