doniyor
doniyor

Reputation: 37876

django - catch multiple exceptions

I have this view function:

def forum(request):
qs = Forum.objects.all()
try:
    f = Forum.objects.filter().order_by('-id')[0] <------------problem
    return render_to_response("forum.html",{'qs':qs,'f':f},context_instance=RequestContext(request))
except Forum.DoesNotExist or IndexError:
    return render_to_response("forum.html",{'qs':qs},context_instance=RequestContext(request))

but it is still giving following error for the problem line above:

IndexError: list index out of range

is my code fine? can i catch multiple exceptions in this way?

Upvotes: 12

Views: 10190

Answers (3)

Jay Modi
Jay Modi

Reputation: 3321

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

Upvotes: 7

Amber
Amber

Reputation: 526593

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

Upvotes: 18

Brandon Taylor
Brandon Taylor

Reputation: 34553

You can catch multiple exceptions in this manner

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

Upvotes: 15

Related Questions