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

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)

Leave a Comment