日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python異常與錯(cuò)誤處理詳細(xì)講解_python

作者:soapcmd ? 更新時(shí)間: 2023-01-27 編程語言

基礎(chǔ)知識(shí)

優(yōu)先使用異常捕獲

LBYL(look before you leap): 在執(zhí)行一個(gè)可能出錯(cuò)的操作時(shí),先做一些關(guān)鍵的條件判斷,僅當(dāng)滿足條件時(shí)才進(jìn)行操作。

EAFP(eaiser to ask for forgiveness than permission): 不做事前檢查,直接執(zhí)行操作。

后者更優(yōu): 代碼簡(jiǎn)潔,效率更高

try語句常用知識(shí)

把更精確的except語句放在前面

異常類派生關(guān)系: BaseException --> Exception --> LookupError --> KeyError

父類被捕獲后子類就不會(huì)再被觸發(fā)

使用else分支

try except else

else: 僅當(dāng)try語句塊里面沒有拋出任何異常時(shí),才執(zhí)行else分支

和finally不同,假如在try語句塊時(shí)碰到了return或者break, 中斷了本次異常,那么即使代碼沒拋出任何異常,else分支內(nèi)的邏輯也不會(huì)被執(zhí)行

而finally里的語句,無論如何都會(huì)被執(zhí)行,哪怕已經(jīng)執(zhí)行了return

使用空raise語句

>>> def incr_by_key(d, key):
...     try:
...         d[key] += 1
...     except KeyError:
...         print('here')
...         raise
...
>>> d = {'a': 1}
>>> incr_by_key(d, 'b')
here
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in incr_by_key
KeyError: 'b'
>>> d['c'] += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

當(dāng)一個(gè)空raise語句出現(xiàn)在except塊里時(shí),它會(huì)原封不動(dòng)地重新拋出當(dāng)前異常

拋出異常,而不是返回錯(cuò)誤

使用上下文管理器

__enter__ __exit__

>>> class DummyContext:
...     def __init__(self, name):
...         self.name = name
...     def __enter__(self):
...         return f"{self.name} -- something"
...     def __exit__(self, exc_type, exc_val, exc_db):
...         print("Exiting")
...         return False
...
>>> with DummyContext('foo') as name:
...     print(f'Name: {name}')
...
Name: foo -- something
Exiting

用于替代finally 語句清理資源

__exit__里面清理資源。

此外__exit__也可以用來對(duì)異常進(jìn)行二次處理然后拋出,或是忽略某種異常等等。

用戶忽略異常

一般可以捕獲異常后pass

但是也可以:

     def __exit__(self, exc_type, exc_val, exc_db):
         if exc_type == SomeException:
             return True
         return False

此外:使用contextlib里面的suppress也可以實(shí)現(xiàn)相同的功能

使用contextmanage裝飾器

>>> @contextmanager
... def create_con_obj(host, port, timeout=None):
...     conn = create_conn(host, port, timeout=timeout)
...     try:
...         yield conn
...     finally:
...         conn.close()

yield前面的語句會(huì)在進(jìn)入管理器時(shí)執(zhí)行(類似:__enter__

之后的邏輯會(huì)在退出管理器時(shí)執(zhí)行(類似:__exit__

原文鏈接:https://blog.csdn.net/weixin_44596902/article/details/128270006

欄目分類
最近更新