What is the proper way to raise an exception in Python?

Question:

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.

Asked By: Anton Koval'

||

Answers:

Both are proper; the latter form lets you attach arguments to your exception:

if len(sys.argv) == 1:
   raise EmptyArgs('Specify at least 1 argument')

See the documentation for the raise statement

Python 2 had a few more options, these have been dropped from Python 3, where you could pass the exception class and arguments as a tuple, but Python 2 is now long gone.

Answered By: Martijn Pieters

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!'
Answered By: nneonneo

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.

Answered By: Anurag Uniyal
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.