Exception Handling in Python

Source: Internet
Author: User

Several exception handling methods are built into Python.

1 Try Except

A = 10b = 0try:    i = a/bexcept Exception, e:    integer division or modulo by Zero# First executes the contents of the Try statement block, and if it performs normally, skip exc EPT content; If the try statement block does not function properly, then executes the contents of the except statement block tightly; 

A = 10b = 0try:    i = a/bexcept Exception, e:    print efinally:    Print 101
>>> integer division or modulo by zero
101
# Executes the contents of the Try statement block first, and if it executes normally, skips the except content; If the try statement block does not function properly, then executes the contents of the EXCEPT statement block closely ; finally executes a finally statement block, ( The finally statement block is executed regardless of whether the try module is functioning properly )

2 Assert statement

>>> assert 3>2, ' error '

# 3>2 equation set, no results returned

>>> assert 1>2, ' error '
Traceback (most recent):
File "C:\Users\Administrator\Desktop\xy.py", line 1, <module>
Assert 1>2, ' error '
Assertionerror:error
# 1>2 equation is not true, throws an exception

3 Raise statements

>>> for I in range (5):         if i = = 2:            raise ValueError # (ValueError is the system-specified error type)
# Raise Exception (' i = = 2 ') #抛出自定义的错误类型 else: printi, Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\xy.py", line 4, <module>
Raise ValueError
ValueError
‘‘‘
0
1

Traceback (most recent):
File "C:\Users\Administrator\Desktop\xy.py", line 4, <module>
Raise Exception (' i==2 ')
exception:i==2
‘‘‘

Exception Handling in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.