Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a cleaner way to approach try except in python

So, let say I have 3 different calls called something, something1 and something2.

and right now, im calling it like

try:
   something
   something1
   something2
except Keyerror as e:
   print e

Note that in the above code, if something fails, something1 and something2 will not get executed and so on.

The wanted outcome is

try:
    something
except KeyError as e:
    print e
try:
    something1
except KeyError as e:
    print e
try:
    something2
except KeyError as e:
    print e

How can I achieve the above code without so many try except blocks.

EDIT:

So, the answer I chose as correct worked. But some of the others worked as well. I chose that because it was the simplist and I modified it a little.

Here is my solution based on the answer.

runs = [something, something1, something2]
for func in runs:
    try:
        func()
    except Keyerror as e:
        print e
like image 883
Cripto Avatar asked Dec 03 '22 22:12

Cripto


1 Answers

You could try this, assuming you wrap things in functions:

for func in (something, something1, something2):
    try:
        func()
    except Keyerror as e:
        print e
like image 125
orlp Avatar answered Dec 09 '22 15:12

orlp