The python exception handling mechanism is similar to Java, using the try-except-finally structure.
Try-except Detecting anomalies
Format
Copy the Code code as follows:
Try
Try_statement
Except (ErrorType1, ErrorType2), E:
Handle_statement
Finally
Finally_statement
Instance
Copy CodeThe code is 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 for scenarios where the resource is finally freed up, because it automatically frees the owning resource and does not need to be displayed to release the resource
Format
Copy the Code code as follows:
With context_expr [as Var]:
With_statement
raise throws an exception
Format
Copy the Code code as follows:
Raise exception[, args] or raise Exception (args)
Instance
Copy CodeThe code is as follows:
Raise Exception (' exampleexception ')
Assertion
Detecting key points of the program, triggering Asserterror (assertion error) when the assertion is unsuccessful
The format is as follows
Copy the Code code as follows:
Assert expression[, arguements]