7

I was wondering if its possible to write a handling exceptions like with 2 or more except with different task to do.

I'm using Django==1.6.1 and Python 2.7

try:
    foo_instance = foo.objects.get(field_name='unknown')

except foo.DoesNotExist:
    new_rec = foo.objects.create(field_name='unknown')
    new_rec.save()

    foo_instance = foo.objects.get(field_name='unknown')

except foo.MultipleObjectsReturned:
    foo_list = foo.objects.filter(field_name='unknown')
    for record in foo_list[1:]:
       print 'Deleting foo id: ', record.id
       record.delete()

    foo_instance = foo.objects.get(field_name='unknown')
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
Charlesliam
  • 1,293
  • 3
  • 20
  • 36
  • It's still python, you can do this. Is there a problem with the code you've provided? – alecxe May 05 '14 at 03:21
  • http://stackoverflow.com/questions/6095717/python-one-try-multiple-except – sfletche May 05 '14 at 03:24
  • Thanks alecxe. The traceback pointing me to the second except line. – Charlesliam May 05 '14 at 03:27
  • But finally found the cause of my error. THe original code for `foo_list` is `em_list = EquipModel.objects.filter(make=ppp_detail[i]))`. It has an extra right parenthesis. > – Charlesliam May 05 '14 at 03:27
  • sorry sfletche..fail to search that link. Thanks for the link – Charlesliam May 05 '14 at 03:28
  • Was wondering why my `DoesNotExist` exception was not taking...looks like it needs to be `except {{Model}}.DoesNotExist:`, where `{{Model}}` is the name of whatever model we're working with. Thanks for adding this example, helped get me out of a bind! – twknab May 17 '17 at 09:19

1 Answers1

11

You could use multiple try: except: but in your current scenario Why don't you use get_or_create ?

try: expect: contain all errors on 'Exception'. for this syntax is all

except Exception as e:

get_or_create(defaults=None, **kwargs)

A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

This reduces your above code to -

 obj, created = foo.objects.get_or_create(field_name='unknown')
 if created:
     obj.save()

I think get_or_create raises IntegrityError or MultipleObjectsReturned, to handle those simply wrap it in a try:

try:
    obj, created = foo.objects.get_or_create(field_name='unknown')
    if created:
        obj.save()
except IntegrityError: 
    #do something
except MultipleObjectsReturned:
    #do something else
except Exception as e:
    raise e
Nilesh Chavan
  • 361
  • 3
  • 10
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264