15👍
✅
You can catch multiple exceptions in this manner
try:
...
except (Forum.DoesNotExist, IndexError) as e:
...
17👍
When you have this in your code:
except Forum.DoesNotExist or IndexError:
It’s actually evaluated as this:
except (Forum.DoesNotExist or IndexError):
where the bit in parentheses is an evaluated expression. Since or
returns the first of its arguments if it’s truthy (which a class is), that’s actually equivalent to merely:
except Forum.DoesNotExist:
If you want to actually catch multiple different types of exceptions, you’d instead use a tuple:
except (Forum.DoesNotExist, IndexError):
6👍
If you want to log/handle each exception, then you can do it like this.
from django.core.exceptions import ObjectDoesNotExist
try:
your code here
except KeyError:
logger.error('You have key error')
except ObjectDoesNotExist:
logger.error('Object does not exist error')
- How can I create a partial search filter in Django REST framework?
- Django: How can I find which of my models refer to a model
- Adding Autoincrement field to existing model with Django South?
- Django JSON De-serialization Security
Source:stackexchange.com