Try-Catch
截斷錯誤
可能有更好的選擇「with」
待進化!
基本使用
try:
a = int(input('輸入 0~9:'))
if a>10:
raise
print(a)
except :
print('有錯誤喔~')
else:
print('沒有錯!繼續執行!') # 完全沒錯才會執行這行
finally:
print('管他有沒有錯,繼續啦!') # 不論有沒有錯都會執行這行 參考資料
拋出錯誤
錯誤詳細資訊
另種方式獲取錯誤檔名與行數
錯誤列表參考
https://www.runoob.com/python/python-exceptions.html
於FastAPI中,支持狀態的回傳
使用「HTTPException」傳出即可,不需要額外在外層包catch統一處理。
但這無法截獲「真正的意外」,萬一有意料外狀況仍會導致服務中止...目前除了每個API入口包try/catch之外,沒有測成功統一的介面處理。
[舊方法]用額外catch擷取覆寫
https://fastapi.tiangolo.com/tutorial/handling-errors/ https://steam.oxxostudio.tw/category/python/basic/try-except.html
Last updated