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