gurney alex
gurney alex

Reputation: 13655

arguments for / against `raise Exception(message)` in Python

I'm working with a framework and the source code is raising exceptions using the Exception class (and not a subclass, either framework specific or from the stdlib) in a few places, which is is not a good idea in my opinion.

The main argument against this idiom is that it forces the caller to use except Exception: which can catch more than what is meant, and therefore hide problems at lower stack levels.

However, a quick search in the Python documentation did not come up with arguments against this practice, and there are even examples of this in the tutorial (although things which are OK in Python scripts may not be OK at all in a Python framework in my opinion).

So is raise Exception considered pythonic?

Upvotes: 2

Views: 112

Answers (2)

Ethan Furman
Ethan Furman

Reputation: 69240

No, it is not. At the very minimum the framework should provide its own exception class, and probably should have several (depending on the variety of things that could go wrong).

As you said, except Exception will catch way too much and is not good practice.

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251568

From PEP 8:

Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class.

Upvotes: 7

Related Questions