python --- exception handling try, except

Abnormal: python using a special object called an exception to management errors that occur during program execution.

When an error occurs, it creates an exception object, if prepared for exception handling, the program continues to run, if it is not treatment for abnormal conduct of the proceedings, after the program encounters an error throws an exception, and returns a traceback, which contains the report of the exception.

Abnormal use try-except block for processing, try-except block so that the specified action python, python encounter and tells how to do this anomaly

>>>try:
...     print(5/0)
... except ZeroDivisionError:
...     print("except")
...
except

By a possible fault code in try-except block of code, the code may increase the ability to withstand an error, block also contains else block, depending on the try-except block code can be successfully executed on the else block (FIG not trigger the abnormal, so the content except the code block is not performed, executed else)

>>> try:
...     print(5/1)
... except:
...     print("except")
... else:
...     print("else")
...
5.0
else

try-except-else-finally: try-except block may also contain a finally block, regardless of which try statement is correct, finally in the code is always executed

try:
    print(5/1)
except:
    print("except")
else:
    print("else")
finally:
    print("finally")

5.0
else
finally

# test except

try:
    print(5/0)
except:
    print("except")
else:
    print("else")
finally:
    print("finally")

except
finally

 

 

 

Published 56 original articles · won praise 1 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_41363156/article/details/100174097