Error handling
C Programming Lesson 20 2:19 English narration · English + 中文 subtitles burned in
Chapters
Transcript
In many languages, a function that cannot do its job will throw an exception, and somewhere up the call chain someone catches it.
在很多语言里,一个做不成事的函数会抛出异常, 然后在调用链的某个上层有人接住它。
C has nothing of the kind.
C 完全没有这一套。
A C function reports trouble through its return value, and the caller checks it — every time, right there at the call.
C 的函数通过返回值来报告问题, 而调用者要去检查它——每一次,就在调用的那一行。
Which means an unchecked return value is not a small oversight.
这意味着,一个没被检查的返回值,不是一个小疏忽。
It is the error handling, missing.
它就是缺失了的错误处理本身。
That raises an obvious problem.
这就带出一个明显的问题。
If the return value is now carrying "did it work", where does the actual answer go?
如果返回值现在用来表示“成没成功”,那真正的答案去哪儿了?
Through an out-pointer.
通过一个输出指针。
The caller passes the address of a variable, and on success the function writes the answer into it.
调用者传进一个变量的地址, 成功时函数把答案写进去。
So two things come back from one call: a verdict and a result.
于是一次调用带回来两样东西:一个判定,和一个结果。
A function can only return one value directly, and this convention is how C gets around that.
函数直接返回的值只能有一个, 而这个约定就是 C 绕开这一点的办法。
Now the part people get wrong.
现在说人们最常做错的那一步。
When the function fails, it must not write anything through the out-pointer.
当函数失败时,它绝不能通过输出指针写任何东西。
It is tempting to store a nought there to be tidy, but a nought would look like a real answer to anyone who forgot to check the code.
为了“干净”,人很想往那里存一个 0, 但对一个忘了检查返回码的人来说,0 看起来就像一个真实的答案。
Left untouched, the caller's variable keeps whatever it had, and that is fine — the caller was told not to use it, by the minus one it just received.
不去动它,调用者的变量就保持原样, 这没问题——它刚收到的那个 -1,已经告诉它别用这个值了。
The third task puts that in a situation where it obviously matters: taking money out of an account.
第三道题把这件事放进了一个明显要紧的场景:从账户里取钱。
If there is enough in the account, work out the new balance, write it through the pointer, and return nought.
如果账户里余额够,就算出新的余额,通过指针写回去,返回 0。
If there is not, refuse and change nothing — return minus one and leave the balance exactly as it was.
如果不够,就拒绝,并且什么都不改—— 返回 -1,让余额原封不动。
A bug here does not print the wrong number; it moves money that was never there.
这里出 bug,结果不是打印了一个错误的数字; 而是动了一笔本来就不存在的钱。
Four things to take with you.
带走四点。
One: C has no exceptions, so trouble comes back as a value.
第一:C 没有异常,所以问题是以一个值的形式回来的。
Two: return nought for success and minus one for failure.
第二:成功返回 0,失败返回 -1。
Three: the real answer travels through an out-pointer.
第三:真正的答案通过输出指针传出去。
Four: on failure, leave the out-pointer untouched.
第四:失败时,不要碰那个输出指针。
Now do the three tasks — the middle one also has to decide whether the text it was given is a number at all.
现在去做那三道题—— 中间那一题还得判断给你的这段文字到底是不是一个数字。