This article describes how to handle exceptions in Python. This article describes how to detect exceptions in try-retry T and how to use the context manager (... As... Statement), raise raises exceptions, assertions, and so on. For more information, see The python exception handling mechanism. it is similar to java and uses the try-try T-finally structure.
Try-try T to detect exceptions
Format
The code is as follows:
Try:
Try_statement
Except t (ErrorType1, ErrorType2), e:
Handle_statement
Finally:
Finally_statement
Instance
The code is as follows:
#! /Usr/bin/python
Try:
A = 12
B = 0
C = a/B
Except t Exception, e:
Print "Exception occurs:", e
Finally:
Print "finally handle! "
Context manager (... As... Statement)
The with statement is particularly applicable to scenarios where the resource is first opened and finally released, because it automatically releases the occupied resources and does not need to be explicitly released.
Format
The code is as follows:
With context_expr [as var]:
With_statement
Raise exception
Format
The code is as follows:
Raise Exception [, args] or raise Exception (args)
Instance
The code is as follows:
Raise Exception ('exampleexception ')
Assertions
Checks the key points of the program. AssertError is triggered when the AssertError is unsuccessful)
The format is as follows:
The code is as follows:
Assert expression [, arguements]