tchakravarty
tchakravarty

Reputation: 10954

Custom Exceptions in Python

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?

Upvotes: 3

Views: 794

Answers (1)

BrenBarn
BrenBarn

Reputation: 251345

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

Upvotes: 4

Related Questions