'What is the proper way to raise an exception in Python? [duplicate]

Here is the simple code:

import sys

class EmptyArgs(StandardError):
    pass

if __name__ == "__main__":
    # The first way to raise an exception
    if len(sys.argv) == 1:
       raise EmptyArgs
    # The second way to raise an exception
    if len(sys.argv) == 1:
       raise EmptyArgs()

Which way is "more" correct? Both are working. Note: In my real code, the exception is exactly the same as I declared: without a message and arguments.



Solution 1:[1]

It is not recommended to raise an exception without arguments, i.e., raising the exception class is not the way to go. Just do something like this:

raise MyException()

Because in Python 3.0, a similar case has been removed for good:

raise Exception, "foo"

There should be one-- and preferably only one --obvious way to do it.

Solution 2:[2]

The two forms are equivalent; they both end up throwing an instance of EmptyArgs. From the documentation:

If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value.

The "second object" referred to above is the (optional) second argument to raise:

raise EmptyArgs, 'Invalid input!'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2