[Solved]-Django – catch multiple exceptions


You can catch multiple exceptions in this manner

except (Forum.DoesNotExist, IndexError) as e:


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


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

from django.core.exceptions import ObjectDoesNotExist

    your code here
except KeyError:
    logger.error('You have key error')
except ObjectDoesNotExist:
    logger.error('Object does not exist error')

Leave a comment