Here is the simple code:
import sys
class EmptyArgs(StandardError):
pass
if __name__ == "__main__":
#first way to raise exception
if len(sys.argv) == 1:
raise EmptyArgs
#second way to raise exception
if len(sys.argv) == 1:
raise EmptyArgs()
Which way is "more" correct? Both are working.
Note: In my real code, exception is exactly the same as I declared: without message and arguments.
解决方案
Both are proper; the latter form let's you attach arguments to your exception:
if len(sys.argv) == 1:
raise EmptyArgs('Specify at least 1 argument')
You can also pass in the arguments as a second value as a tuple in the raise statement:
if len(sys.argv) == 1:
raise EmptyArgs, ('Specify at least 1 argument',)
but a single non-tuple value will work too, and is regarded as a single argument:
if len(sys.argv) == 1:
raise EmptyArgs, 'Specify at least 1 argument'
and a third value to raise let's you specify an alternate traceback, which then is used instead of a traceback that would be generated for the current location in the code:
if len(sys.argv) == 1:
raise EmptyArgs, ('Specify at least 1 argument',), traceback_object
See the documentation for the raise statement
Note that when you do use arguments for your exception, The Python styleguide PEP 8 prefers you provide an exception instance, and not a class:
When raising an exception, use raise ValueError('message') instead of the older form raise ValueError, 'message'.
The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3.
Python 3 will no longer support that form.