Wednesday, April 19, 2017
Django Reminder Handling Custom Exceptions
Django Reminder Handling Custom Exceptions
In Django, if we try to get an object that does not exist, the DoesNotExist exception will be raised.
However, the following code does not work out of the box, albeit being the obvious solution to handle such exception:
try:
img = Image.objects.get(pk = 42)
except DoesNotExist:
print "Image Does Not Exist"
This is because the DoesNotExist exception is actually an attribute of an model object.
Therefore, we would need to use this exception express to handle it (so we dont have to import the error manually)
except Image.DoesNotExist:
print "Image Does Not Exist"
To handle more than one possible exception, use the standard Python way to add more exception cases:
except (ValueError, Image.DoesNotExist):
#do something.
Labels:
custom,
django,
exceptions,
handling,
reminder
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.