PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

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

 August 05, 2022     exception, python     No comments   

Issue

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

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

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 lets 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.



Answered By - Martijn Pieters
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing