django - catch multiple exceptions django - catch multiple exceptions django django

django - catch multiple exceptions


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):


You can catch multiple exceptions in this manner

try:    ...except (Forum.DoesNotExist, IndexError) as e:   ...


If you want to log/handle each exception, then you can do it like this.

from django.core.exceptions import ObjectDoesNotExisttry:    your code hereexcept KeyError:    logger.error('You have key error')except ObjectDoesNotExist:    logger.error('Object does not exist error')