使用raise語句引發一個異常,可以使用一個類(應該是Exception的子類)或者實例參數來作為raise的引發對象。使用類時,程序會自動創建實例,如
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
raise Exception('hyperdrive overload')
Exception: hyperdrive overload
可以使用try/except實現捕捉異常,如
try: x = input(":") y = input(":") PRint x/yexcept ZeroDivisionError: print "hello exception"#結果如下:>>> :10:25>>> :1:0hello exception
再次引發異常,如
class MuffledCalculator: muffled = False def calc(self, expr): try: return eval(expr) except ZeroDivisionError: if self.muffled : #如果屏蔽標志開啟,則處理異常 print "Division by zero is illegal" else:#如果屏蔽標志未開啟,則再次引發異常 raise#結果如下:>>> clc = MuffledCalculator()>>> clc.calc('10/2')5>>> clc.calc('10/0') #沒有屏蔽Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> clc.calc('10/0') #沒有屏蔽 File "E:/work/Code/python/test.py", line 137, in calc return eval(expr) File "<string>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero>>> clc.muffled = True>>> clc.calc('10/0') #有屏蔽Division by zero is illegal
except后面不帶參數可以捕捉所有的異常, 可以通過在ty/except后加一個except語句或者在except語句中用元組將多個異常類型列出來實現捕捉多個異常,如下:
try: x = input(":") y = input(":") print x/yexcept (ZeroDivisionError, TypeError), e: print e#結果如下>>> :10:0integer division or modulo by zero
在ty/except后加一個else語句可以在沒有引發異常的情況下執行一些語句,如
while True: try: x = input(":") y = input(":") print x/y except Exception,e: print e else : print "Ah,.... it successed" break#結果>>>:10:0integer division or modulo by zero:10:25Ah,.... it successed
finally子句 -- finally子句肯定會被執行,不管try子句中是否發生異常,主要用于關閉文件或者網絡套接字。
新聞熱點
疑難解答