我想寫一個類,它可以處理在我的應用程序中引發的錯誤。這樣我就可以在一個類中更改錯誤消息的格式。Python自定義錯誤類來處理異常
class ErrorMessage(Exception):
def __init__(self, error, classname):
self.error = error
self.classname = classname
self.errormsg = "scriptname.py, {0}, error={1}".format(self.classname, self.error)
print self.errormsg
class LoadFiles():
try:
something-bad-causes-error
except Exception,e:
raise ErrorMessage(e, "LoadFiles")
此刻我的腳本打印機自定義錯誤,但它繼續退出這一行之前打印的完整回溯「提高的ErrorMessage(即‘LoadFiles’)」
scriptname.py, LoadFiles, error= LoadFiles instance has no attribute 'config'
Traceback (most recent call last):
File "run.py", line 95, in <module>
scriptname().main()
File "run.py", line 54, in main
self.loadfiles()
File "run.py", line 45, in loadfiles
"removed" = LoadFiles(self.commands).load_files()
File "dir/core/loadfiles.py", line 55, in load_files
raise ErrorMessage(e, "LoadFiles")
scriptname.core.errormessage.ErrorMessage
任何想法如何解決這個問題?
感謝
爲什麼你還在使用'except Exception,e:'語法?新的語法支持[從2.6](https://docs.python.org/2/whatsnew/2.6.html#pep-3110-exception-handling-changes),現在已經超過8年了。 – jonrsharpe
爲什麼LoadFiles是一個類?它對我來說看起來像一個功能。 – tyteen4a03
我知道這是一個旁白,但如果你還沒有,看一看標準的例外和警告套件。可能有一個適合你的用例。 – rshield