網站首頁 編程語言 正文
基礎知識
優先使用異常捕獲
LBYL(look before you leap): 在執行一個可能出錯的操作時,先做一些關鍵的條件判斷,僅當滿足條件時才進行操作。
EAFP(eaiser to ask for forgiveness than permission): 不做事前檢查,直接執行操作。
后者更優: 代碼簡潔,效率更高
try語句常用知識
把更精確的except語句放在前面
異常類派生關系: BaseException --> Exception --> LookupError --> KeyError
父類被捕獲后子類就不會再被觸發
使用else分支
try except else
else: 僅當try語句塊里面沒有拋出任何異常時,才執行else分支
和finally不同,假如在try語句塊時碰到了return或者break, 中斷了本次異常,那么即使代碼沒拋出任何異常,else分支內的邏輯也不會被執行
而finally里的語句,無論如何都會被執行,哪怕已經執行了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'
當一個空raise語句出現在except塊里時,它會原封不動地重新拋出當前異常
拋出異常,而不是返回錯誤
使用上下文管理器
__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__
也可以用來對異常進行二次處理然后拋出,或是忽略某種異常等等。
用戶忽略異常
一般可以捕獲異常后pass
但是也可以:
def __exit__(self, exc_type, exc_val, exc_db): if exc_type == SomeException: return True return False
此外:使用contextlib里面的suppress也可以實現相同的功能
使用contextmanage裝飾器
>>> @contextmanager ... def create_con_obj(host, port, timeout=None): ... conn = create_conn(host, port, timeout=timeout) ... try: ... yield conn ... finally: ... conn.close()
yield前面的語句會在進入管理器時執行(類似:__enter__
)
之后的邏輯會在退出管理器時執行(類似:__exit__
)
原文鏈接:https://blog.csdn.net/weixin_44596902/article/details/128270006
相關推薦
- 2022-01-20 Syntax Error: TypeError: this.getOptions is not a
- 2022-10-23 C#中使用Microsoft?Unity記錄日志_C#教程
- 2022-03-16 ASP.NET?Core開發Docker部署_基礎應用
- 2023-10-09 雙token登錄
- 2022-03-21 詳解C語言動態內存的分配_C 語言
- 2022-11-21 Qt實現小功能之復雜抽屜效果詳解_C 語言
- 2022-10-21 C++調用matlab函數的實例_C 語言
- 2022-05-15 C++設計模式中的觀察者模式一起來看看_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支