Python(10)錯誤和異常

Python(10)錯誤和異常

  • 檢測和處理異常
  • 上下文管理
  • 觸發異常
  • 斷言
  • 標準異常

檢測和處理異常

第一種語句:try-except

try:
    pass
except Exception, e: # 捕獲所有異常
    raise e          # 拋出捕獲的異常

第二種語句:try-except-except-except

try:
    pass
except Exception1, reason1:
    raise
except Exception2, reason2:
    raise
except Exception3, reason3:
    raise

第三種語句:處理多個異常的except語句

try:
    pass
except (Exception1,Exception2), reason:
    raise

第四種語句:try-except-else語句

try:
    pass
except Exception, e:
    raise e
else:    # try範圍中沒有檢測到異常時,執行else語句
    pass

第五種語句:try-except-finally語句

try:
    pass
except Exception, e:
    raise e
finally: # 無論異常是否發生,是否捕捉到,都會執行該語句
    pass

第六種語句:try-except-else-finally

try:
    pass
except Exception, e:
    raise
else:
    pass
finally:
    pass

第七種語句:try-finally

try:
    pass
finally:
    pass

上下文管理

with open('/etc/pas','r') as f:
    for eachline in f:

觸發異常

try:
    pass
except Exception, e:
    raise

斷言

斷言語句:如果斷言成功不採取任何措施,否則觸發斷言錯誤的異常

assert 1 == 0

Traceback (most recent call last):
  File "E:\code\DA\da.py", line 5, in <module>
    assert 1 == 0
AssertionError

標準異常

Python的常見標準異常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章