Exception Handling
Return a value or raise exception?
Raise exceptions when possible because return values will be ignored: if a routine's returned value can be ignored, a programmer will probably ignore it!
Exceptions cannot easily be ignored, thus can force the programmer to test and then to take some appropriate action in one place: the error handler.
Exception handling may make the code more elegant than return value handling.
Return value handling:
def func(): if a(): ... if b(): ... if c(): ...Exception handling:
def func(): try: a() b() c() except: # Handle exception here
Remove else
Sometimes else is said to be harmful. Eg:
if foo:
a()
elif bar:
b()
else:
c()Should refactor to:
# a(), b() will raise exception on error
if foo:
a()
if bar:
b()
c()这样的代码:
if (someExpression) {
return true;
} else {
return false;
}应该改成:
return someExpression;
Python语言的异常机制
- C语言并不是没有异常处理,完全通过return来判断。
- C语言处理异常的思路是:返回错误(-1),设置errno。
- 函数不能既返回结果又返回错误。
- No news is good news / 没有消息就是最好的消息。
- 最小惊讶原理(Least Surprise Principle): 函数返回值的可预见性:类型一致。
- Duck Typing: 对于Python,有很多没有所谓基类,却行为相似的对象(如 file like objects)。
- 直接将静态语言编程思想套用于动态语言是危险的。
- 解释器错误比运行期错误好。
- 程序崩溃比逻辑错误好:不要捕获 AttributeError,尽量抛出 AttributeError 和 KeyError: 发现逻辑问题的最好机会。
- 了解各种Python异常的含义,尽量使用现有异常类型。
- 先 TypeError 后 ValueError。
- 总结:
- 不要做输入检查:检查只会让输入变得更不可靠
- 不要编写保护性代码:越多的安全策略只会让程序变得更不安全
- 不要容错,让程序崩溃
- 不要处理异常,尽量制造和抛出异常
