Your example exception is most often the preferred way to do things. Wikipedia has a pretty nice description:
The Python style causes the use of exceptions whenever an error condition occurs. Instead of checking access to a file or resource before actually using it, in Python, just go ahead and try to use it by catching an exception if access is denied.
Exceptions are often used as an alternative to an if block (...). The accepted motto is EAFP, or "Easier to ask" for Forgiveness than Permission. "
Exceptions are not necessarily expensive in Python. Again, quoting the Wikipedia example:
if hasattr(spam, 'eggs'): ham = spam.eggs else: handle_error()
... vs:
try: ham = spam.eggs except AttributeError: handle_error()
These two code examples have the same effect, although there will be differences in performance. When spam has attribute eggs, the EAFP sample will run faster. When spam has no attribute eggs (an โexceptionalโ case), the EAFP sample will run slower.
In particular, for Django I would use an exception example. This is the standard way to do something in this area, and the following standards will never be bad :).
source share