Is there a difference between “raise exception()” and “raise exception” without parenthesis?

The short answer is that both raise MyException and raise MyException() do the same thing. This first form auto instantiates your exception.

The relevant section from the docs says:

raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

That said, even though the semantics are the same, the first form is microscopically faster, and the second form is more flexible (because you can pass it arguments if needed).

The usual style that most people use in Python (i.e. in the standard library, in popular applications, and in many books) is to use raise MyException when there are no arguments. People only instantiate the exception directly when there some arguments need to be passed. For example: raise KeyError(badkey).

Leave a Comment