简体   繁体   English

Python自定义错误类来处理异常

[英]Python custom error class to handle Exceptions

I'm trying to write a class which can handle errors raised throughout my application. 我正在尝试编写一个可以处理整个应用程序中引发的错误的类。 This is so I can change the format of the error messages in one class. 这样一来,我可以在一类中更改错误消息的格式。

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")

At the moment my script printers the custom error, however it continues to print the complete traceback before exiting on this line "raise ErrorMessage(e, "LoadFiles")" 目前,我的脚本会打印自定义错误,但是在退出“ raise ErrorMessage(e,“ 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

Any ideas how the fix this? 任何想法如何解决?

Thanks 谢谢

If you just need to exit script on this error, do not raise an exception, just print your error and exit. 如果只需要针对此错误退出脚本,则不要引发异常,只需打印错误并退出即可。 And it's even easier if you don't need your exception to be reusable: 如果您不需要异常可重用,则更加容易:

try:
    something-bad-causes-error
except Exception as e:
    print("scriptname.py, LoadFiles, error={0}".format(e))
    sys.exit(1)

Also it would be better to use logging module to print errors. 同样,最好使用logging模块打印错误。

I think you are missing the point of custom Exceptions, to create an exception class means that some function or logic of your program will throw that custom exception and you would be able to catch it and handle it. 我认为您错过了自定义异常的要点,创建一个异常类意味着程序的某些函数或逻辑将抛出该自定义异常,并且您将能够捕获并处理它。 If you are looking only to parse the output, there is no need to create a custom class: 如果您只想解析输出,则无需创建自定义类:

try:
  something_bad # will raise maybe IndexError or something
except Exception as e:
  print e.message

While with custom classes: 在使用自定义类时:

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

The point is what exception you want to raise 关键是你想提出什么例外

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM