Python錯誤和異常概念

來源:互聯網
上載者:User
Python錯誤和異常概念(總)

1. 錯誤和異常的處理方式

  1. 常見的錯誤

  2. a:NameError

  3. if True:SyntaxError

  4. f = oepn('1.txt'):IOError

  5. 10/0:ZeropisionError

  6. a = int('d'):ValueError

  7. 程式運行中斷:KeyboardInterrupt

2.Python-使用try_except處理異常(1)

try:    try_suiteexcept Exception [e]:    exception_block
  1. try用來捕獲try_suite中的錯誤,並且將錯誤交給except處理

  2. except用來處理異常,如果處理異常和設定捕獲異常一致,使用exception_block處理異常

# case 1try:    undefexcept:    print 'catch an except'
# case 2try:    if undefexcept:    print 'catch an except'
  • case1:可以捕獲異常,因為是執行階段錯誤

  • case2:不能捕獲異常,因為是語法錯誤,運行前錯誤

--

# case 3try:    undefexcept NameError,e:    print 'catch an except',e
# case 4try:    undefexcept IOError,e:    print 'catch an except',e
  • case3:可以捕獲異常,因為設定捕獲NameError異常

  • case4:不能捕獲異常,因為設定IOError,不會處理NameError

Example
import randomnum = random.randint(0, 100)while True:    try:        guess = int(raw_input("Enter 1~100"))    except ValueError, e:        print "Enter 1~100"        continue    if guess > num:        print "guess Bigger:", guess    elif guess < num:        print "guess Smaller:", guess    elif guess == num:        print "Guess OK,Game Over"        break    print '\n'

3. Python使用try_except處理異常(2)

  • try-except:處理多個異常

try:    try_suiteexcept Exception1[e]:    exception_block1except Exception2[e]:    exception_block2except ExceptionN[e]:    exception_blockN

4. Python-try_finally使用

try:    try_suitefinally:    do_finally
  • 如果try語句沒有捕獲錯誤,代碼執行do_finally語句

  • 如果try語句捕獲錯誤,程式首先執行do_finally語句,然後將捕獲的錯誤交給python解譯器處理

5. Python-try-except-else-finally

 try:    try_suite except:    do_except finally:    do_finally
  • 若try語句沒有捕獲異常,執行完try程式碼片段後,執行finally

  • 若try捕獲異常,首先執行except處理錯誤,然後執行finally

6. Python-with_as語句

with context [as var]:    with_suite
  • with語句用來代替try_except_finall語句,使代碼更加簡潔

  • context運算式返回是一個對象

  • var用來儲存context返回對象,單個傳回值或者元祖

  • with_suite使用var變數來對context返回對象進行操作

with語句實質是上下文管理:

  1. 上下文管理協議:包含方法__enter__()__exit()__,支援該協議的對象要實現這兩個方法

  2. 上下文管理器:定義執行with語句時要建立的運行時上下文,負責執行with語句塊上下文中的進入與退出操作

  3. 進入上下文管理器:調用管理器__enter__方法,如果設定as var語句,var變數接受__enter__()方法傳回值

  4. 退出上下文管理器:調用管理器__exit__方法

class Mycontex(object):    def __init__(self, name):        self.name = name    def __enter__(self):        print "__enter__"        return self    def do_self(self):        print "do_self"    def __exit__(self, exc_type, exc_val, exc_tb):        print "__exit__"        print "Error:", exc_type, " info:", exc_valif __name__ == "__main__":    with Mycontex('test context') as f:        print f.name        f.do_self()

whith語句應用情境:

  1. 檔案操作

  2. 進程線程之間互斥對象,例如互斥鎖

  3. 支援內容相關的其他對象

2. 標準異常和自動以異常

1. Python-assert和raise語句

  • rais語句

    • reise語句用於主動拋出異常

    • 文法格式:raise[exception[,args]]

    • exception:異常類

    • args:描述異常資訊的元組

raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
  • assert語句

    • Assert 陳述式:assert語句用於檢測運算式是否為真,如果為假,引發AssertionError錯誤

    • 文法格式:assert expression[,args]

    • experession:運算式

    • args:判斷條件的描述資訊

assert 0, 'test assert'
assert 4==5, 'test assert'

2. Python-標準異常和自訂異常

  • 標準異常

    • python內建異常,程式執行前就已經存在

  • 自訂異常:

    • python允許自訂異常,用於描述python中沒有涉及的異常情況

    • 自訂異常必須繼承Exception類

    • 自訂異常只能主動觸發

class CustomError(Exception):    def __init__(self, info):        Exception.__init__(self)        self.message = info        print id(self)    def __str__(self):        return 'CustionError:%s' % self.messagetry:    raise CustomError('test CustomError')except CustomError, e:    print 'ErrorInfo:%d,%s' % (id(e), e)


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.