mbudge
mbudge

Reputation: 557

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

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

Upvotes: 1

Views: 3290

Answers (2)

Yann
Yann

Reputation: 2522

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.

Upvotes: 1

patito
patito

Reputation: 540

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!

Upvotes: 2

Related Questions