**Exception catch: **
try:
XXXXX1
raise Exception(“xxxxx2”)
except (Exception1,Exception2,……):
xxxx3
else:
xxxxx4
finally:
xxxxxxx5
The raise statement can customize the error message, as above.
The statement after raise will not be executed, because the exception has been thrown, the control flow will jump to the exception capture module.
The except statement can carry multiple exceptions after one except, or it can use multiple statements to catch multiple exceptions and handle them differently.
If the exception caught by the except statement does not occur, the statement block in the except statement will not be executed. But execute the statement in else
In the above statement, the order of try/except/else/finally must be try– except X– except– else– finally, that is, all except must be before else and finally, and else (if any) must be before finally , And except X must be before except. Otherwise, a syntax error will occur.
Both else and finally are optional.
In the above complete statement, the existence of the else statement must be based on the except X or the except statement. If the else statement is used in a try block without an except statement, a syntax error will occur.
Abnormal parameter output:
try:testRaise()
except PreconditionsException as e: #The wording of python3 must use asprint(e)
For custom exceptions, you only need to customize the exception class to inherit the parent class Exception. In the custom exception class, override the init method of the parent class.
classDatabaseException(Exception):
def __init__(self,err='Database error'):
Exception.__init__(self,err)classPreconditionsException(DatabaseException):
def __init__(self,err='PreconditionsErr'):
DatabaseException.__init__(self,err)
def testRaise():
raise PreconditionsException()try:testRaise()
except PreconditionsException as e:print(e)
Note: PreconditonsException is a subclass of DatabaseException.
So if you raise PreconditionException, you can catch both exception classes.
However, if it is raise DatabaseException, PreconditonsException cannot be caught.
Example supplement:
Python custom exception capture exception handling exception
def set_inf(name,age):if not 0< age <120:
raise ValueError('Out of range')else:print('%s is %s years old'%(name,age))
def set_inf2(name,age):
assert 0< age <120,'Out of range'print('%s is %s years old'%(name,age))if __name__ =='__main__':try:set_inf('bob',200)
except ValueError as e:print('Invalid value:',e)set_inf2('bob',200)
This is the end of this article on how python custom captures errors. For more relevant python custom error capture methods, please search ZaLou.Cn
Recommended Posts