yasar
yasar

Reputation: 13758

Is there a difference between raising Exception class and Exception instance?

In Python, I can raise an Exception in two ways

raise ValueError
raise ValueError()

apart from the fact that you can supply exception message in latter case, is there any fundamental difference between these two styles? Should I choose one over the other?

Upvotes: 55

Views: 6374

Answers (2)

astreal
astreal

Reputation: 3513

from the doc both are valid (no unexpected behaviour):

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).

In my opinion, an instance need to be used if you want it to hold data, whether it is a message (as you said) or custom data or whatever.

as @alko said, if you don't give an instance it will instantiate one with no argument.

this won't work if you need a mandatory argument:

>>> class MyError(Exception):
...    def __init__(self, message, data=None):
...       self.msg = message
...       self.data = data or {}
...
>>> raise MyError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes at least 2 arguments (1 given)

Upvotes: 34

alko
alko

Reputation: 48357

To summarize comments: there is no difference. Either syntax will throw ValueError instance. Relevant excerpt from the docs:

If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

Upvotes: 21

Related Questions