above_c_level
above_c_level

Reputation: 3939

Is there a use case for an alternative "exception cause" in Python?

Background

In Python it is possible to suppress the context of an Exception if you raise your Exception from None. PEP 409 describes the rationale behind it. Sometimes you want to show only one meaningful (custom) Exception. With PEP 415 the implementation changes with the following argument:

The main problem with this scheme [from PEP 409] is it complicates the role of __cause__. __cause__ should indicate the cause of the exception not whether __context__ should be printed or not. This use of __cause__ is also not easily extended in the future. For example, we may someday want to allow the programmer to select which of __context__ and __cause__ will be printed.

Question

PEP 419 talks about future use cases. Are there any valid use cases right now (Python 3.3+) for using an alternative exception cause? For example, consider the following code:

    class CustomError(BaseException):
        pass

    class StupidError(BaseException):
        def __init__(self, message='This is just a stupid error.'):
            super(StupidError, self).__init__(message)
            self.message = message

    try:
        value = int('a')
    except Exception:
        raise CustomError('Custom error message') from StupidError

Output:

StupidError: This is just a stupid error.

The above exception was the direct cause of the following exception:

Traceback (most recent call last): (...)
CustomError: Custom error message

Are there any real use cases in which you want to hide the ValueError but show the StupidError? I mean you could give some relevant information in the StupidError which are not present in a mere ValueError? Maybe I am just overthinking this whole thing.

Upvotes: 0

Views: 60

Answers (1)

Josh Honig
Josh Honig

Reputation: 187

Sure. Say you're writing a web app and need to hide sensitive/complicated data from the user.

Say a user tries a request, but the web app backend has trouble reading the necessary data from a MySQL database (for whatever reason). Instead of letting the MySQL module raise the error, which could either expose sensitive information about how the app works internally or just simply confuse the user, I would want to catch it and then throw my custom exception (let's call it serverError). That custom exception would show the user a HTTP 500 page as well as report the error internally so it can be analyzed by a developer to figure out what went wrong and how to prevent it.

This means I only have to write my general error handling code once, and then when I catch an error, I can raise serverError, which takes care of the error reporting for me.

Upvotes: 1

Related Questions