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?
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.
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.
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.
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 | .
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With