The python exception handling mechanism is similar to Java, using a try-except-finally structure.
Try-except Detection exception
Format
Copy Code code as follows:
Try
Try_statement
Except (ErrorType1, ErrorType2), E:
Handle_statement
Finally
Finally_statement
Instance
Copy Code code as follows:
#!/usr/bin/python
Try
A=12
B=0
c = A/b
Except Exception, E:
Print "Exception occurs:", E
Finally
Print "Finally handle!"
Context Manager (With...as ...) Statement)
The WITH statement can be especially useful when you first open the scenario where the resource was last freed, because it automatically frees up the resources that are in the possession and does not need to be shown to release the resources
Format
Copy Code code as follows:
With context_expr [as Var]:
With_statement
raise throws an exception
Format
Copy Code code as follows:
Raise exception[, args] or raise Exception (args)
Instance
Copy Code code as follows:
Raise Exception (' exampleexception ')
assert
Detects the key point of the program, the assertion is unsuccessful when the trigger Asserterror (assertion error)
Format is as follows
Copy Code code as follows:
Assert expression[, arguements]