Skip to content
Advertisement

Python: Multiple try except blocks in one?

Is there a neat way to have multiply commands in the try block so that it basically tries every single line without stopping as soon as one command yields an error?

Basically I want to replace this:

try:
   command1
except:
   pass
try:
   command2
except:
   pass
try:
   command3
except:
   pass

with this:

try all lines:
  command1
  command2
  command3
except:
  pass

Defining a list so I could loop through the commands seems to be a bad solution

Advertisement

Answer

I’d say this is a design smell. Silencing errors is usually a bad idea, especially if you’re silencing a lot of them. But I’ll give you the benefit of the doubt.

You can define a simple function that contains the try/except block:

def silence_errors(func, *args, **kwargs):
    try:
        func(*args, **kwargs)
    except:
        pass # I recommend that you at least log the error however


silence_errors(command1) # Note: you want to pass in the function here,
silence_errors(command2) # not its results, so just use the name.
silence_errors(command3)

This works and looks fairly clean, but you need to constantly repeat silence_errors everywhere.

The list solution doesn’t have any repetition, but looks a bit worse and you can’t pass in parameters easily. However, you can read the command list from other places in the program, which may be beneficial depending on what you’re doing.

COMMANDS = [
    command1,
    command2,
    command3,
]

for cmd in COMMANDS:
    try:
        cmd()
    except:
        pass
Advertisement