I. Exceptions
Python throws an exception when it encounters an error. If the exception object is not captured or processed, the program will backtrack (Traceback) to terminate the operation:
1 print 1/ 023Traceback (most recent call last):4 " D:\coding_file\python_file\TestPython\src\Test\test1.py " in <module>5 print 1/ 06or modulo by Zero
Two. Throwing an exception
Python uses a class or instance argument to invoke the raise statement to throw an exception.
1 RaiseException ("It ' s an exception raised by me.")2 3 Traceback (most recent):4File"D:\coding_file\python_file\TestPython\src\Test\test1.py", Line 1,inch<module>5 RaiseException ("It ' s an exception raised by me.")6Exception:it's An exception raised by me.
Three: Catching multiple exceptions
Python uses try/except to catch exceptions. You can use a tuple to list multiple types of exceptions to achieve a block that captures multiple types of exceptions.
1 Try:2x = input ('Please enter the first number :')3y = input ('Please enter the second number:')4 PrintX/y5 except(Zerodivisionerror, TypeError) as E:6 Printe7 8 Input:9Please enter the first number:1Ten Please enter the second number:0 One A Operation Result: -Integer divisionorModulo by zero
< Span style= "color: #0000ff;" >< Span style= "color: #008080;" >< Span style= "color: #0000ff;" > > Note: except (Zerodivisionerror, TypeError) as E:
/span> E is used for storing exception information, which can be used for subsequent printing exception information; Before Python 3.0 can writeexcept (Zerodivisionerror, TypeError), E:
Four. Require the user to re-enter
You can use a looping statement to make the program constantly require re-entry when an error occurs:
1 whileTrue:2 Try:3x = input ('Please enter the first number :')4y = input ('Please enter the second number:')5result = x/y6 Print 'x/y equals', result7 except(Zerodivisionerror, TypeError) as E:8 Print 'Invalid Input:', E9 Print 'Please enter again.'Ten Else: One Break A - Input: -Please enter the first number:1 the Please enter the second number:0 - - Operation Result: -Invalid Input:integer Divisionormodulo by Zero + Please enter again. -Please enter the first number:
Program exits normally (via Else:break statement) when no exception occurs
Five. Cleanup after an exception occurs
The finally statement is used to clean up after possible exceptions
1 Try:2x = input ('x =?:')3y = input ('y =?:')4 PrintX/y5 except(Zerodivisionerror, TypeError, Nameerror) as E:6 Printe7 Else:8 Print 'No problem!'9 finally:Ten Print ' done!'
In the above code, the finally clause is bound to be executed regardless of whether the try statement has an exception
[Python Learning Diary] Exception handling for Python