3

I am trying to understand how to use custom exceptions in Python using the try-except construction.

Here is a simple example of a custom exception:

# create custom error class
class CustomError1(Exception):
    pass

I attempted to use it like so:

# using try-except
def fnFoo1(tuple1, tuple2):
    try:
        assert(len(tuple1) == len(tuple2))
    except AssertionError:
        raise(CustomError1)
    return(1)
fnFoo1((1,2), (1, 2, 3))

This raises the CustomeError1 but also raises the AssertionError, which I would like to subsume in CustomError1.

The following does what I want, but does not seem to be the way that exceptions should be handled.

# use the custom error function without try-catch
def fnFoo2(tuple1, tuple2):
    if len(tuple1) != len(tuple2): raise(CustomError1)
    print('All done!')
fnFoo2((1,2), (1, 2, 3))

What is the way to write custom exceptions that hide other exceptions?

3
  • Have a look at this: ankurankan.github.io/blog/2014/06/03/custom-assert-method-in-python/ Commented Jun 5, 2014 at 7:06
  • What version of Python 3 are you using? I seem to recall there were some changes in exception behavior in later 3.x versions. Commented Jun 5, 2014 at 7:09
  • @brenbarn python 3.3.1 Commented Jun 5, 2014 at 7:10

1 Answer 1

4

According to PEP 409 you should be able to suppress the original exception context by using raise CustomError1 from None. This is also documented here:

using raise new_exc from None effectively replaces the old exception with the new one for display purposes

This functionality was added in Python 3.3. In versions from 3.0 to 3.2, it was not possible to hide the original exception (ouch).

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

1 Comment

Super, thanks. I thought I had missed something because it seemed like such a simple thing to try and achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.