[英]does merry handle exceptions in python?
我正在尋找更多的 Pythonic 方法來處理 Python 中的錯誤,我發現我很快樂
如果您從未聽說過這里是文檔: https : //github.com/miguelgrinberg/merry
所以我用 merry 寫了一些代碼
from merry import Merry
merry = Merry()
@merry._try
def write_to_file(filename,data):
with open(filename,'w') as file_obj:
file_obj.write(data)
@merry._except(FileNotFoundError)
def fileNotFoundError():
print("File not found")
@merry._except(Exception)
def catch_all(e):
print(f"exception occured :{e}")
@merry._else
def else_clause():
print("no exceptions occured")
path = "C:/Users/User/Desktop1/dataHere.txt"
text = "top secret information"
write_to_file(path,text)
請注意,我改變了提高的路徑
找不到文件錯誤
我以為 merry 會處理錯誤,但我得到了這個輸出:
[快樂] 異常被捕獲
回溯(最近一次調用):文件“C:\\python36\\lib\\site-packages\\merry.py”,第 26 行,在包裝器中 ret = f(*args, **kwargs) 文件“C:/Users/User /Desktop/merrymerry.py", line 7, in write_to_file with open(filename,'w') as file_obj: FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/j.sinjaradze/Desktop1/dataHere .txt'文件未找到
是不是我做錯了什么,或者只是快樂不像我預期的那樣工作?
我認為你誤解了你的輸出/快樂是如何工作的。 在您的輸出中,您有:
[merry] Exception caught
這表明 merry 捕獲了異常。 然后是異常的回溯,默認情況下快樂輸出,然后是
File not found
這是你的結果
def fileNotFoundError():
print("File not found")
所以一切正常
附錄。 為什么merry會輸出異常?
在merry的源代碼中(見你鏈接的github),有這一行(merry.py:46):
self.logger.exception('[merry] Exception caught')
self.logger
之前是從logging.getLogger(logger_name)
調用創建的,異常函數打印除了先前發生的異常的回溯之外還提供的消息(有關詳細信息,請參閱python 日志記錄文檔)。
從源代碼中,我看不到在不觸及merry.py
源代碼的情況下改變該行為的merry.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.