Getting started with python (7): error handling try/except statements in python

In the process of programming, you often encounter errors in the written program, so you often need to constantly debug, because these errors will make the entire program stop running, but you can use try/except statements to catch exceptions in python

try / except statement is try to detect whether there is an error in the statement, if any, the except it will capture the exception information and processing .

Examples:

try:
    result = 5/0 #除以0会产生运算错误
except Exception as e: #出现错误会执行except
    print (e)   #把错误信息打印出来

Insert picture description here
The above code first executes the statement in the try, an error occurs, except captures the exception information and prints it out.

except can handle exceptions (such as printing) or not printing them, as follows:

try:
    result = 5/0 #除以0会产生运算错误
except: #出现错误会执行except
    pass    #空语句,不做任何事情

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45154565/article/details/109351054