djangopython-2.7

Except statement in Django


Code from Django tutorial:

try:
    selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# The rest of code...

Why we have two these exceptions here: KeyError and Choice.DoesNotExist?

Isn't they are equal? What's the difference between them?


Solution

  • KeyError may be raised by request.POST['choice']. It's a Python error for dictionaries raised when you try to access a key that doesn't exist.

    DoesNotExist is a Django framework error for the DB interface raised when you try to get an object from the database and it doesn't exist.

    Choice.DoesNotExist inherits from DoesNotExist but only for the Choice model, and thus is raised when you do something like Choice.objects.get(...) and the instance does not exist.