[Solved]-Django – catch multiple exceptions

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

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

Leave a comment