標籤:1.2 執行個體 exception str traceback 方式 ast argument 資訊
- 常式:使用except並加上異常類型
# -*- coding: UTF-8 -*- try: fh = open("a.txt",‘w‘) fh.write("This is a file for Exception test!")except IOError: print "Error, file not found or access failure!"else: print "Successful!"
輸出:
[email protected]:~/code$ python test.py Successful![email protected]:~/code$ cat a.txt This is a file for Exception [email protected]
- 通過開啟a.txt也能看到
write()是不加分行符號的
1.2. 為了測試,我們先把a.txt得寫入權限給去掉,再重新執行以上代碼,可以發現無法寫入而產生的異常
chmod -w a.txt[email protected]:~/code$ python test.py Error, file not found or access failure!
- 使用異常而不帶任何異常類型
try: 正常的操作 ......................except: 發生異常,執行這塊代碼 ......................else: 如果沒有異常執行這塊代碼
- 使用異常而帶多種異常類型
try: 正常的操作 ......................except(Exception1[, Exception2[,...ExceptionN]]]): 發生以上多個異常中的一個,執行這塊代碼 ......................else: 如果沒有異常執行這塊代碼
- try...finally語句:無論是否發生異常都將執行最後的代碼
# -*- coding: UTF-8 -*- try: fh = open("a.txt",‘w‘) fh.write("This is a file for Exception test!")finally: print "Error: File not found or access error"
輸出:
[email protected]:~/code$ python test.py Error: File not found or access errorTraceback (most recent call last): File "test.py", line 3, in <module> fh = open("a.txt",‘w‘)IOError: [Errno 13] Permission denied: ‘a.txt‘[email protected]:~/code$ chmod +w a.txt [email protected]:~/code$ python test.py Error: File not found or access error
- 異常的參數:一個異常可以帶上參數,可以作為輸出時的異常參數
try: 正常的操作 ......................except ExceptionType, Argument: 你可以在這輸出 Argument 的值...
執行個體:
# -*- coding: UTF-8 -*- def temp_convert(var): try: return int(var) except ValueError,Arg: print "參數不包含數字:",Argprint temp_convert(‘xyz‘)
輸出:
[email protected]:~/code$ python test.py 參數不包含數字: invalid literal for int() with base 10: ‘xyz‘None
觸發異常:
raise [Exception [, args [, traceback]]]
語句中 Exception 是異常的類型(例如,NameError)參數標準異常中任一種,args 是自已提供的異常參數。
# -*- coding: UTF-8 -*-def mye(level): if level < 1: raise Exception,"Invalid Error!" #觸發異常後,後面的代碼>將不會被執行try: mye(0)except Exception,err: print 1,errelse: print 2
輸出:
[email protected]:~/code$ python test.py 1 Invalid Error!
- 使用者自訂的異常
通過建立一個新的異常類,程式可以命名它們自己的異常。異常應該是典型的繼承自Exception類,通過直接或間接的方式。
- 以下為與RuntimeError相關的執行個體,執行個體中建立了一個類,基類為RuntimeError,用於在異常觸發時輸出更多的資訊;
- 在try語句塊中,使用者自訂的異常後執行except塊語句,變數 e 是用於建立Networkerror類的執行個體。
# -*- coding: UTF-8 -*-class NetworkError(RuntimeError): def __init__(self, arg): self.args = argtry: raise NetworkError("Bad hostName")except NetworkError,e: print e.args
輸出:
[email protected]:~/code$ python test.py (‘B‘, ‘a‘, ‘d‘, ‘ ‘, ‘h‘, ‘o‘, ‘s‘, ‘t‘, ‘N‘, ‘a‘, ‘m‘, ‘e‘)
問題:為什麼輸出一個一個字母?以後再答
Python 異常 2018-08-01