Using try except in python to catch exception

try:
<statement block 1>
except:
<statement block 2>

or it could be:

try:
<statement block 1>
except <exception type>:
<statement block 2>
Only in this specific exception type will the execution of statement block 2

Because the name of the exception type is customized within Python, we do not need to string it

Code:

try:
    num = eval(input("请输入一个整数:"))
    print(num ** 2)
except NameError:
    print("输入不是整数")

Advanced use of try except:
try:
<statement block 1>
except:
<statement block 2>
else:
<statement block 3>
finally:
<statement block 4>

The code in try statement block 1
If an error occurs, proceed to the content of statement block 2
If no exception occurs, proceed to the content of statement block 3
Whether or not an exception occurs, the content of statement block 4 will be executed

Published 22 original articles · Like 3 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/helloworld987456/article/details/104259405