Python自定义错误类来处理异常
问题描述:
我想写一个类,它可以处理在我的应用程序中引发的错误。这样我就可以在一个类中更改错误消息的格式。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
任何想法如何解决这个问题?
感谢
答
如果你只需要在这个错误退出脚本,不引发异常,只是打印错误并退出。而且它的,即使你不需要你的例外是可重复使用的简单:
try:
something-bad-causes-error
except Exception as e:
print("scriptname.py, LoadFiles, error={0}".format(e))
sys.exit(1)
而且这将是更好地使用logging
模块打印错误。
答
我认为你错过了自定义异常的意义,创建一个异常类意味着你的程序的某些函数或逻辑会抛出这个自定义异常,你将能够捕获并处理它。如果你正在寻找只是解析输出,没有必要创建一个自定义类:
try:
something_bad # will raise maybe IndexError or something
except Exception as e:
print e.message
虽然使用自定义类:
class DidNotHappen(Exception):
def __init__(*args, **kwargs):
# do something here
def my_function(something_happens):
if somehting_happens:
cool
else:
raise DidNotHappen
my_function(True) # cool
my_function(False) # Raises DidNotHappen exception
的关键是要提高
什么异常祝你好运!
为什么你还在使用'except Exception,e:'语法?新的语法支持[从2.6](https://docs.python.org/2/whatsnew/2.6.html#pep-3110-exception-handling-changes),现在已经超过8年了。 – jonrsharpe
为什么LoadFiles是一个类?它对我来说看起来像一个功能。 – tyteen4a03
我知道这是一个旁白,但如果你还没有,看一看标准的例外和警告套件。可能有一个适合你的用例。 – rshield