面试题答案
一键面试- 抛出的异常类型:会抛出
json.JSONDecodeError
异常。 - 捕获并处理异常的代码示例:
import json
json_str = '{name: "John"}' # 格式错误的JSON字符串
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"JSON数据格式错误: {e}")
上述代码中,使用 try - except
语句捕获 json.JSONDecodeError
异常,并向用户打印友好的错误提示。