When working with Python's error handling, you may encounter two syntaxes in except statements: ',' and 'as'. This article aims to clarify the difference between these two syntaxes and guide their appropriate use.
try:
pass
except Exception, exception:
pass
In Python versions prior to 2.6, this syntax was the only way to assign an exception to a variable. The comma separates the exception class from the variable name. For example, the above code would assign the exception to the variable exception.
try:
pass
except Exception as exception:
pass
Introduced in Python 2.6, the as syntax allows for clearer and more explicit assignment of an exception to a variable. This syntax assigns the exception to the variable specified after the keyword as. Continuing the example above, this code assigns the exception to the variable exception.
The legality of the as syntax depends on the Python version:
While both syntaxes are valid in Python 2.6 , it is recommended to use the as syntax. It is less ambiguous and forward compatible with Python 3.x, where it becomes the required syntax.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3