[Django]-Possible to have multiple Python except statements when using try (without searching for a specific except)?

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

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

Leave a comment