Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 472
doniyor Avatar asked May 26 '13 00:05

doniyor


People also ask

How do you catch multiple exceptions in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you pass multiple exceptions in catch block?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.

Can I have multiple excepts in Python?

Python Multiple ExceptsIt is possible to have multiple except blocks for one try block. Let us see Python multiple exception handling examples. When the interpreter encounters an exception, it checks the except blocks associated with that try block. These except blocks may declare what kind of exceptions they handle.

Can one block handle multiple exceptions?

Handle Multiple Exceptions in a catch Block In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .


1 Answers

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):
like image 65
Amber Avatar answered Oct 05 '22 14:10

Amber