Exceptions · 异常处理
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
出错的时候
- 运行时错误通常会让程序崩溃。
- 异常(exception)是 Python 发出的"出问题了"的信号。
- 异常处理让你捕获它,并继续运行。
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- 把有风险的代码放进
try:代码块。 - 如果它抛出异常,就会运行
except:代码块,而不是崩溃。 - 如果没有出错,
except代码块会被跳过。
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
捕获正确的错误
- 写明你预期的错误类型:
except ValueError:。 ValueError表示用于转数字的文字有误;ZeroDivisionError表示除以零。- 捕获具体类型,才不会把别的 bug 也一起隐藏掉。
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally 与 raise
finally:代码块总会运行,无论是否出错 —— 适合做清理工作。raise让你主动发出一个错误信号。raise ValueError("message")会停止代码,除非有什么东西捕获它。
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
为什么重要
- 一个健壮的程序不应该因为坏的输入就崩溃。
- 处理异常让它能提醒用户,然后继续运行。
- 它还能确保文件和其他资源被干净地关闭。
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
常见错误
- 捕获具体错误(
except ValueError:),不要用光秃秃的except:。 - 只把有风险的那行放进
try。
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
现在轮到你
- 使用
try/except(最后一个任务还要用raise)。 - 按检查答案来测试你的代码。
try / except
Code runs in try; if it fails, control jumps to except. · 代码在 try 中运行;一旦出错,就跳到 except。
Write safe_int(text) that returns · 返回值 int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · 编写 safe_int(text),返回 int(text)。如果文字不是有效的数字,就捕获 ValueError,改为返回 -1。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write divide(a, b) that returns · 返回值 a / b. If b is 0, catch the ZeroDivisionError and return None instead. · 编写 divide(a, b),返回 a / b。如果 b 是 0,就捕获 ZeroDivisionError,改为返回 None。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return · 回报 the new balance (balance - amount). · 编写 withdraw(balance, amount)。如果 amount 大于 balance,就 raise ValueError。否则返回新的余额(balance - amount)。
Click Run to see the output here. · 点击“运行”查看此处输出。