–
错误处理 高级语言通常都内置了一套try...except...finally...的错误处理机制 当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码, 即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。 try: print('try...') r = 10 / 0 print('result:', r) except ZeroDivisionError as e: print('except:', e) raise e finally: print('finally...') print('end') 执行结果 try... Traceback (most recent call last): except: division by zero finally... File "D:\python练习\exec.py", line 8, in <module> raise e File "D:\python练习\exec.py", line 4, in <module> r = 10 / 0 ZeroDivisionError: division by zero 下面这种更复杂的也可以 try: print('try...') r = 10 / int('2') print('result:', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError:', e) else: print('no error!') finally: print('finally...') print('END') 使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用,比如函数main()调用foo(),foo()调用bar(),结果bar()出错了, 这时,只要main()捕获到了,就可以处理 不需要在每个可能出错的地方去捕获错误,只要在合适的层次去捕获错误就可以了。这样一来,就大大减少了写try...except...finally的麻烦。 def foo(s): return 10/int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: print('error:', e) finally: print('finally...') if __name__ == '__main__': main() 执行结果 error: division by zero finally... 人为抛出错误 def foo(s): n = int(s) if n == 0: raise ValueError('invalid value: %s' % s) return 10/n def bar(): try: foo('0') except ValueError as e: print('value error') raise bar() 执行结果 执行结果 Traceback (most recent call last): value error File "D:\python练习\exec.py", line 15, in <module> bar() File "D:\python练习\exec.py", line 10, in bar foo('0') File "D:\python练习\exec.py", line 5, in foo raise ValueError('invalid value: %s' % s) ValueError: invalid value: 0
–
评论前必须登录!
注册