First, the definition
Python uses an exception object to represent an exception condition. When an error is encountered, an exception is thrown, and if the exception object is not processed or snapped, the program terminates execution with the so-called backtracking (traceback).
Each exception is an instance of some class that can be raised and can be captured in a number of ways.
Second, raise statement throws an exception
Raise"<stdin>" in <module>Exception Raise Exception ('error error'<stdin> " in <module>exception:error error
Exception is the base class for all exception classes. Some other common exception classes can be viewed in the manual. All two of the above examples throw exceptions through the raise statement. The second example adds an error message.
Third, catch the exception
The ability to catch exceptions can be achieved through the TRY/EXCEPT statement. For specific exceptions, you can add an exception class after except, as follows:
Try : = input (") = input (") print x/yexcept zerodiyisionerror: print" "
如果except后面什么异常类也不加,那么就会捕捉所有异常。
If you catch an exception and want to re-throw it, you can call raise without parameters.
Try : = input (") = input (") print x/yexcept zerodiyisionerror: Raise
Iv. Capturing multiple exceptions
The first method can use multiple except clauses for each case description.
Try: x= Input ('Enter The first number:') y= Input ('Enter The second number:') Printx/yexceptZerodiyisionerror:Print "The second number can ' t be zero!"exceptTypeError:Print "That is ' t a number!Of course, you can also list the exception type as a tuple.
Try : = input (") = input (") print x/yexcept (TypeError, nameerror): print" Your numbers were bogus ... "
V. Accessing the Exception object itself
Try : = input (") = input (") print x/yexcept (TypeError, Nameerror), E: print E
You can print the error by using the above method.
Vi. using the Else, finally statement
When catching an exception, you can also use the else, finally statement to perform some operations together.
x =NoneTry: x= 1/0exceptNameerror:Print "Unknown Variable"Else:#An else statement is executed when no exception occurs Print "That went well!"finally:#The finally statement is executed regardless of whether there is an exception Print "Cleaning up"?
Python Learning--exceptions