Is this a Pythonic way to handle custom errors?

32 Views Asked by At
try:
    try:
        # important operations
    except Exception:
        raise CustomException

    # general operations

except CustomException:
    # "Custom logs"
except Exception:
    # "General exception occurred"

I'm using Python 2.7. I also considered the answer of this post, but I feel that is not the proper way to do it, since you use "except Exception" as a general box for other exceptions.

For CustomException I intend something like:

class CustomException(Exception):
    """This exception will be raised when..."""
1

There are 1 best solutions below

0
jsbueno On

There is no problem with this pattern if ou happen to need it. And I can imagine mechanisms where that would be useful.

Just take care to proper instantiate your exceptions - raise CustomException() vs just raise CustomException

Also, if you where using a newer version of the language, you could use raise from:

...
except Exception as inner_error:
    raise CustomException from inner_error
...

That would correctly wrap all the information from the general exception in your CustomException instance.