在Python中,具有特殊功能的标识符称为关键字。关键字是Python语言自己已经使用的了,不允许开发者自己定义和关键字相同名字的标识符。本文主要介绍Python except 关键字(keyword)。

Python 关键字

例如:

如果该语句引发错误,则打印输出"Something went wrong":

try:
    x > 3
except:
    print("Something went wrong")

1、定义和用法

except关键字在try... except块中使用。 如果try块引发错误,它将要运行定义的代码块。

可以为不同的错误类型定义不同的代码块,并在有问题的情况下执行对应的代码块,请参见下面的示例。

2、使用示例

例如:

NameError和TypeError不同的异常分别输出不同的消息

x = "hello"

try:
    x > 3
except NameError:
    print("You have a variable that is not defined.")
except TypeError:
    print("You are comparing values of different type")

例如:

尝试执行一条引发错误的语句,但没有定义的错误类型(在这种情况下为ZeroDivisionError):

try:
    x = 1/0
except NameError:
    print("You have a variable that is not defined.")
except TypeError:
    print("You are comparing values of different type")
except:
    print("Something else went wrong")

例如:

如果没有出现错误,使用else关键字打印输出信息:

x = 1

try:
    x > 10
except NameError:
    print("You have a variable that is not defined.")
except TypeError:
    print("You are comparing values of different type")
else:
    print("The 'Try' code was executed without raising any errors!")

3、相关函数

try关键字

finally关键字

Python 关键字

推荐文档

相关文档

大家感兴趣的内容

随机列表