来自 Django 教程的代码:
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# The rest of code...
为什么我们在这里有两个例外:KeyError和Choice.DoesNotExist?
他们不是平等的吗?他们之间有什么区别?
来自 Django 教程的代码:
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# The rest of code...
为什么我们在这里有两个例外:KeyError和Choice.DoesNotExist?
他们不是平等的吗?他们之间有什么区别?
KeyError可能由request.POST['choice']. 这是当您尝试访问不存在的键时引发的字典的 Python 错误。
DoesNotExist是当您尝试从数据库中获取对象但它不存在时引发的 DB 接口的 Django 框架错误。
Choice.DoesNotExist继承自DoesNotExist但仅适用于Choice模型,因此当您执行类似Choice.objects.get(...)的操作并且实例不存在时会引发。
如果request.POST['choice']失败将生成KeyError.
另一个是:
exception ObjectDoesNotExist
The DoesNotExist exception is raised when an object is not found for the given parameters of a query.
现在,如果您不KeyError输入,系统将引发错误,并且您except将无用,因为KeyError未捕获,反之亦然。