1. try & except 原程式: 1 import math 2 3 while True: 4 text = raw_input('> ') 5 if text[0] == 'q': 6 break 7 x = float(text) 8 y = math.log10(x) 9 print ...
1. try & except
原程式:
1 import math 2 3 while True: 4 text = raw_input('> ') 5 if text[0] == 'q': 6 break 7 x = float(text) 8 y = math.log10(x) 9 print "log10({0}) = {1}".format(x, y)View Code
這段代碼接收命令行的輸入,當輸入為數字時,計算它的對數並輸出,直到輸入值為 q
為止。
但是當輸入0或者負數時,會報錯。
修改後的程式:
import math while True: try: text = raw_input('> ') if text[0] == 'q': break x = float(text) y = math.log10(x) print "log10({0}) = {1}".format(x, y) except ValueError: print "the value must be greater than 0"View Code
一旦 try
塊中的內容出現了異常,那麼 try
塊後面的內容會被忽略,Python會尋找 except
裡面有沒有對應的內容,如果找到,就執行對應的塊,沒有則拋出這個異常。
運行結果:
> -1 the value must be greater than 0 > 0 the value must be greater than 0 > 1 log10(1.0) = 0.0 > qView Code
捕捉所有類型錯誤:
將except
的值改成 Exception
類,來捕獲所有的異常。
import math while True: try: text = raw_input('> ') if text[0] == 'q': break x = float(text) y = 1 / math.log10(x) print "1 / log10({0}) = {1}".format(x, y) except Exception: print "invalid value"View Code
運行結果:
> 1 invalid value > 0 invalid value > -1 invalid value > 2 1 / log10(2.0) = 3.32192809489 > qView Code
進一步完善後的程式:
import math while True: try: text = raw_input('> ') if text[0] == 'q': break x = float(text) y = 1 / math.log10(x) print "1 / log10({0}) = {1}".format(x, y) except ValueError: print "the value must be greater than 0" except ZeroDivisionError: print "the value must not be 1" except Exception: print "unexpected error"View Code
運行結果:
> 1 the value must not be 1 > -1 the value must be greater than 0 > 0 the value must be greater than 0 > qView Code
2. finally
不管 try 塊有沒有異常, finally 塊的內容總是會被執行,而且會在拋出異常前執行,因此可以用來作為安全保證,比如確保打開的文件被關閉。
try: print 1 / 0 finally: print 'finally was called.'
out: finally was called.
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-13-87ecdf8b9265> in <module>() 1 try: ----> 2 print 1 / 0 3 finally: 4 print 'finally was called.' ZeroDivisionError: integer division or modulo by zero
如果異常被捕獲了,在最後執行:
try: print 1 / 0 except ZeroDivisionError: print 'divide by 0.' finally: print 'finally was called.' out: divide by 0. finally was called.View Code