首頁  >  文章  >  後端開發  >  Python錯誤與異常概念

Python錯誤與異常概念

高洛峰
高洛峰原創
2017-02-28 10:32:451597瀏覽

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_suite
except Exception [e]:
    exception_block
  1. try用來捕捉try_suite中的錯誤,並且將錯誤交給except處理

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

# case 1
try:
    undef
except:
    print 'catch an except'
# case 2
try:
    if undef
except:
    print 'catch an except'
  • case1:可以捕獲異常,因為是運行時錯誤

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

--

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

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

num = 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 &#39;\n&#39;
3. Python使用try_except處理例外(2)

    #try -except:處理多個異常
  • try:
        try_suite
    except Exception1[e]:
        exception_block1
    except Exception2[e]:
        exception_block2
    except ExceptionN[e]:
        exception_blockN
  • 4. Python-try_finally使用
try:
    try_suite
finally:
    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. 進入上下文管理員:調用管理器
  4. __enter__

    方法,如果設定as var語句,var變數接受__enter__()方法傳回值

  5. 退出上下文管理器:調用管理器
  6. __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_val
    
    
    if __name__ == "__main__":
        with Mycontex(&#39;test context&#39;) as f:
            print f.name
            f.do_self()
  7. whith語句應用場景:

    檔案操作
  1. #進程執行緒之間互斥對象,例如互斥鎖
  2. 支援上下文的其他物件
  3. 2. 標準異常和自動以異常

1. Python-assert和raise語句

    rais語句
    • reise語句用於主動拋出異常
    • 語法格式:raise[exception[,args]]
    • exception:異常類別
    • #args:描述例外資訊的元組
    • raise TypeError, &#39;Test Error&#39;
      raise IOError, &#39;File Not Exit&#39;
##assert語句
  • 斷言語句:assert語句用來偵測表達式是否為真,如果為假,引發AssertionError錯誤
    • 語法格式:assert expression[,args]
    • experession:表達式
    • args:判斷條件的描述訊息
    • assert 0, &#39;test assert&#39;
      assert 4==5, &#39;test assert&#39;
    • 2. Python-標準異常與自訂異常

標準異常
  • #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 &#39;CustionError:%s&#39; % self.message
      
      
      try:
          raise CustomError(&#39;test CustomError&#39;)
      except CustomError, e:
          print &#39;ErrorInfo:%d,%s&#39; % (id(e), e)

更多Python錯誤與異常概念相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn