Skip to content

Chain exceptions where appropriate #15986

@eric-wieser

Description

@eric-wieser

Picking up from #15731, there are many places in numpy where we do something like:

try:
    something_which_throws_typeError
except TypeError:
    raise ValueError("a clearer explanation of what went wrong")

It would produce a marginally clearer error if we could change these to use traceback chaining. Our two options are either:

  1. The inner error provides valuable information that is not present in the outer error. We should use from e.
    try:
        something_which_throws_typeError
    except TypeError as e:
        raise ValueError("a clearer explanation of what went wrong") from e
  2. The inner error provides no valuable information that is not present in the outer error. We should use from None:
    try:
        some_dict[name]
    except KeyError:
        raise ValueError("The name %s is not supported" % name) from None
    In that example all the information from the KeyError is already in the message of the new error, so there is no point chaining

An example of such a change would be this line of this otherwise-discarded patch.

For now, I would recommend we only apply this to cases where the exception is thrown unconditionally, as other cases can be more nuanced.


Please see this list for potential places to contribute. Special thanks to @nkleinbaer for compiling the list!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions