What's an elegant way to get the same exception multiple times?

I have Python code that tries to put together several different database queries before it concludes that the database is empty and refuses. Here's a simplified example:

try:
    result = Object.get(name="requested_object")
except Object.DoesNotExist:
    try:
        result = Object.get(name="default_object")
    except Object.DoesNotExist:
        try:
            result = Object.get(pk=1)
        except Object.DoesNotExist:
            print "The database is empty!"
            raise

      

Please note that the exception I am trying to catch is the same thing. There must of course be a way to do this without unnecessary repetition and nesting. How can I achieve the same behavior without nested try ... except statements?

+3


source to share


2 answers


for args in [{'name':"requested_object"}, {'name':"default_object"}, {'pk':1}]:
    try:
        result = Object.get(**args)
    except Object.DoesNotExist as e:
        continue
    else:
        break
else:
    raise e

      



It's not clear what kind of exception you want to raise, if you never find what you want, you might have to adjust that part. Also, the scope of exception values โ€‹โ€‹changed in Python 3, so e

it will not be up-scaled.

+7


source


Nested and complex control blocks are easier to read when wrapped in a function:

def result():
    try:
        return Object.get(name="requested_object")
    except Object.DoesNotExist:
        pass

    try:
        return Object.get(name="default_object")
    except Object.DoesNotExist:
        pass

    return Object.get(pk=1) # NB: no "try" here. If it going to fail, let it fail

      



This way you avoid excessive indentation and "mental jumps" such as break

/ continue

.

+2


source







All Articles