網(wǎng)站首頁 編程語言 正文
基礎(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
相關(guān)推薦
- 2022-02-13 Chrome控制臺(tái)報(bào)錯(cuò):無法加載 SourceMap 錯(cuò)誤:狀態(tài)代碼 404,net::ERR_HT
- 2023-01-20 React?Redux管理庫示例詳解_React
- 2022-12-22 Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解_Android
- 2022-07-22 yaml文件的加載使用
- 2022-01-20 淺談關(guān)于 && , || , ? : , ?? , ?. 的運(yùn)算方式以及用法
- 2022-06-23 C#獲取計(jì)算機(jī)硬件與操作系統(tǒng)的相關(guān)信息_C#教程
- 2022-10-15 Go?編程復(fù)雜數(shù)據(jù)類型?Map_Golang
- 2022-12-10 docker編譯IJKPlayer播放器記錄詳解_docker
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支