3

This is my current code:

def get_queryset(self)
    pk = self.kwargs['pk']

    try: 
        postD = PostD.objects.get(pk=pk)
        # In the line below, PostReply.objects.filter(postD=postD) is
        # not guaranteed to exist, so I am using a try statement.
        return PostReply.objects.filter(postD=postD)

    except:
        postY = PostY.objects.get(pk=pk)
        # In the line below, PostReply.objects.filter(postY=postY) is
        # not guaranteed to exist either, so this may raise an error.
        return PostReply.objects.filter(postY=postY)

    # Here, I want one last except statement to execute if the above try
    # and except statements fail... Is it okay to just add another except
    # statement like this:

    except:
        postR = PostR.objects.get(pk=pk)
        # If the above try and except statement fail, this is guaranteed to
        # not throw an error.
        return PostReply.objects.filter(postR=postR)

I know I can do something like this:

try:
    # code
except ObjectDoesNotExist:
    # code
except:
    # last part of code

but it is not guaranteed that I will be getting an ObjectDoesNotExist error (I'm not guaranteed what error I will be getting). So I'm wondering if there is a way of having more than one except statement without specifying what exception to look for? Is the way I did it above (where I just have try: except: except: okay to use?

SilentDev
  • 20,997
  • 28
  • 111
  • 214

2 Answers2

3

A bare except: will catch anything and everything, so it makes no sense to have a second except block in this case.

Possibly you wanted to put the code inside your first except block into another nested try/except block.

Note: Pokemon exception handling is considered bad coding style, and it's better if you only try to catch the actual exceptions which you intend to handle - in this case, only catching the DoesNotExist should be sufficient.

You might consider using a loop to refactor this:

PostModels = {
    'postD': PostD,
    'postY': PostY,
    'postR': PostR,    
}

for k,Post in PostModels.items():
    try: 
        post = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        pass
    else:
        return PostReply.objects.filter(k=post)
else:
    # all 3 lookups failed, how do you want to handle this?
wim
  • 338,267
  • 99
  • 616
  • 750
1

Since the first except will catch any exception raised from the try block, the only way "the above try and except statements fail" is if code in the first except block raises an exception. To catch that, you should wrap it directly with try/except:

def get_queryset(self)
    try:
        ...
    except:
        try:
            <<original first except-block here>>>
        except:
            <<original second except-block here>>>

Also, in general you should avoid bare except:.

shx2
  • 61,779
  • 13
  • 130
  • 153