2

What is better?

class CustomException(Exception):
    pass

class CustomSomething(object):
    def do_something(self, xml):
        try:
            lxml.etree.parse(xml)
        except LxmlError as e:  # LxmlError class is only example
            raise CustomException(e)

or just

class CustomSomething(object):
    def do_something(self, xml):
        lxml.etree.parse(xml)

When should I use a try/except block and raise custom exceptions, and when should I let whatever's calling my function handle it?

1
  • This is an interesting question. I don't see an answer to it in PEP 8. Commented Apr 9, 2015 at 1:03

2 Answers 2

1

In general, I don't see a need to add a try/except block when you're just raising another exception. Usually, the exception you raise will be pretty much the same as the one raised by whatever you're calling (because the problem is still the same). This isn't supported by any official documentation I can find (other than "[s]imple is better than complex"); the best I could find was the list of built-in exceptions, which says this:

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions

That just seems to explain how to create custom exceptions, though, not when to.

Sign up to request clarification or add additional context in comments.

1 Comment

There's a more serious problem with re-raising a custom exception as shown in the first example which is that you're going to clobber the traceback in the original exception. In general it's best practice to only try-except and re-raise a custom exception if you've actually done some mitigation in the except block and you want to give calling code a chance to handle the leftovers.
1

In this particular case I don't see a good reason to have a custom exception. I introduce custom exceptions only when I need to pass back more information than the built-in exception to the caller. Even if I had to do some special handling of the built-in exception, I'd just re-raise the original exception once I'm done with my part.

Only other reason I can think of having custom exceptions is to have a consistent interface to the class, including all the exceptions it can raise.

More important thing to make sure is that the do_something method documents all the exceptions it can raise (built-in or custom), so that user is aware of what to catch.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.