Python 異常 2018-08-01

來源:互聯網
上載者:User

標籤:1.2   執行個體   exception   str   traceback   方式   ast   argument   資訊   

  1. 常式:使用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!
  1. 使用異常而不帶任何異常類型
try:    正常的操作   ......................except:    發生異常,執行這塊代碼   ......................else:    如果沒有異常執行這塊代碼
  1. 使用異常而帶多種異常類型
try:    正常的操作   ......................except(Exception1[, Exception2[,...ExceptionN]]]):   發生以上多個異常中的一個,執行這塊代碼   ......................else:    如果沒有異常執行這塊代碼
  1. 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
  1. 異常的參數:一個異常可以帶上參數,可以作為輸出時的異常參數
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
  1. 觸發異常:

    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!
  1. 使用者自訂的異常
    通過建立一個新的異常類,程式可以命名它們自己的異常。異常應該是典型的繼承自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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.