Exceptions
Python for A-Level CS Lesson 3 2:06 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Ask Python to turn the word hello into a number and it raises an exception — a value error.
让 Python 把 "hello" 变成数字,它会抛出一个异常——ValueError。
And an exception that nobody handles stops the program on the spot: the line after it does not run at all.
而一个没有人处理的异常,会当场终止程序: 它后面那一行根本不会执行。
For a calculation you are running yourself, that is fine and even helpful.
如果这是你自己跑的一次计算,这没问题,甚至挺有用。
For a program serving other people, it is a crash.
但如果这是一个为别人服务的程序,那就是一次崩溃。
Put the risky line in a try block and give it an except to fall back on.
把有风险的那一行放进 try 块,再给它一个 except 作为退路。
Hand it good text and the try block finishes normally — you get forty-two.
传入合法的文本,try 块正常执行完——你得到 42。
Hand it hello and the exception is caught, so the except block runs instead and you get None.
传入 "hello",异常被接住, 于是 except 块被执行,你得到 None。
Exactly one of the two runs, and the program carries on either way.
两个块里恰好有一个会运行,而无论走哪条路,程序都能继续下去。
Name the error you expect.
写出你预期的那个错误的名字。
Writing except with nothing after it will catch everything — including a misspelled variable name in your own code, three lines further down.
写一个后面什么都不跟的 except,它会接住一切—— 包括你自己代码里、三行之后拼错的一个变量名。
That is the worst kind of bug, because the program does not fail; it quietly returns your fallback value, and a typo of yours looks exactly like bad input from the user.
那是最糟糕的一类 bug,因为程序不会失败; 它会安静地返回你的备用值, 而你自己的拼写错误,看起来就和用户输入的坏数据一模一样。
The third task goes the other way: instead of catching an exception, you raise one.
第三道题反过来:不是接住异常,而是主动抛出一个。
If the amount is more than the balance, that withdrawal cannot happen, so you say so — you are signalling a problem rather than handling one.
如果取款金额超过余额,这笔取款就不能发生,于是你把这件事说出来—— 你是在报告一个问题,而不是在处理一个问题。
And this is stronger than returning an error code, because a code can be ignored and an exception cannot: the caller either handles it or the program stops.
而这比返回一个错误码更有力, 因为错误码可以被忽略,异常不能: 调用者要么处理它,要么程序就停下来。
Four things to take with you.
带走四点。
One: try holds the risky line, and except runs if it fails.
第一:try 放有风险的那一行,出错时执行 except。
Two: name the error you expect — never a bare except.
第二:写出你预期的错误名——绝不要写裸的 except。
Three: finally runs whether it failed or not, which is where cleanup goes.
第三:finally 无论失败与否都会执行,收尾工作放在那里。
Four: raise signals a problem the caller must handle.
第四:raise 抛出一个调用者必须处理的问题。
Now do the three tasks.
现在去做那三道题。