Python KeyError 异常

定义和用法

当使用字典中不存在的键时,会引发 KeyError 异常。

可以通过 try...except 语句捕获 KeyError,参见以下示例。

实例

例子 1

如果尝试使用不存在的键访问字典,将会引发 KeyError

fruit = {"name": "apple", "color": "red"}
print(fruit["price"])  # 尝试访问不存在的键 "price"

亲自试一试

例子 2:异常处理

使用 try...except 语句处理 KeyError

fruit = {"name": "apple", "color": "red"}
try:
  print(fruit["price"])  # 尝试访问不存在的键
except KeyError:
  print("错误!您正在尝试访问字典中不存在的键!")
except:
  print("发生了其他错误")

亲自试一试