Home  >  Article  >  Backend Development  >  How to get multiple exceptions in one line

How to get multiple exceptions in one line

anonymity
anonymityOriginal
2019-05-24 16:03:022740browse

Method to get multiple exceptions in one line: [try-except(exception1, exception2) as e]. In Python, the try except statement is used to catch and handle exceptions. If you need to catch multiple exceptions uniformly, you can use parentheses for processing.

How to get multiple exceptions in one line

try-except in Python can capture and handle exceptions. When multiple exceptions are encountered and need to be captured and processed uniformly, parentheses can be used for unified processing, except ( Use intervals between multiple exceptions) as e.

Python is an interpreted, object-oriented, high-level programming language with dynamic data types. Python was invented by Guido van Rossum at the end of 1989, and the first public release was released in 1991. Like the Perl language, Python source code also follows the GPL (GNU General Public License) agreement.

Python provides two very important functions to handle exceptions and errors that occur when python programs are running.

There may be errors like this:

try:
    # 可能错的地方
except:
    # 如果错了执行这里

There may also be errors like this:

try:
    # 可能错的地方
except IDontLikeYourFaceException:
    # 给爷笑一个
except YouAreTooShortException:
    # 踩高跷

How to get multiple exceptions in one line?

Answer: You can use parentheses to solve it

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

Or, for Python 2 only:

except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass

Separate with commas method only works in Python 2.6 and 2.7, but not in Python 3; now, you should use as.

The above is the detailed content of How to get multiple exceptions in one line. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn