22

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.

0

3 Answers 3

31

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

4 Comments

In his case it makes no differences, PEP 3109 says: EXCEPTION may be an exception class or an instance of an exception class. The problem occurs when you are using tuples, like in your second example. This is no longer valid.
@PaoloMoretti agree, but still I don't recommend it, like I don't recommend tabs, and I hope it eventually is removed from python 3.x
You want tabs to be removed? :o (Kidding, I actually agree with the object over type statement; not with the tabs one though)
@poke sorry I was not talking abt tabs but about raising Exception Class
1

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!' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.