Each programming language will have its own exception handling mechanism, although each has its own characteristics, but basically all the same, so what is the powerful exception handling mechanism in Python?
First, exception:
Python uses an exception object to represent an exception, and an exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with backtracking:
1 >>> 1/02Traceback (most recent call last):3 " <stdin> " in <module>4or modulo by zero
In fact, each exception is an instance of a class that can be thrown and can be snapped in many ways, so that the program can catch the error and handle it instead of having the entire program fail. The more common exceptions are listed below:
Second, catch the exception and deal with
1, using Try/except for exception handling, the syntax is as follows:
Try
Program block
Except (Exception Class 1, Exception Class 2 ...)
Processing statements
else: #没有异常时执行
Program block
Finally: #都要执行, typically used to close files, database connections, and so on.
Processing statements
1>>>Try:2... x = input ("First number :") 3... y = input ("Second:")4...Printx/y5...exceptZerodivisionerror:6...Print("Division not Zero")7 ... 8First Number:109 second:0TenDivision notZero
2, abnormal full capture
Except does not follow any objects, but is not recommended.
Fifth. exception handling in Python