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

Question:

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?

Asked By: yasar

||

Answers:

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.

Answered By: alko

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)
Answered By: astreal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.