Python: Multiple try except blocks in one?

14k views Asked by At

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

5

There are 5 answers

0
Colonel Thirty Two On BEST 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
6
Charlie Martin On

Actually, your second choice is exactly hat you want. As soon as any command raises an exception, it will through to the except, and includes the information of which exception and at what line it occurred. You can, if you want, catch different exceptions and do different things with

try:
  command1
  command2
except ExceptionONe:
  pass
except Exception2:
  pass
except:
  pass   # this gets anything else.
1
Tristan Vigil On

You can except multiple errors within the same except statement.For example:

   try:        
    cmd1
    cmd2
    cmd3    
   except:
      pass

Or you could make a function and pass the error and the cmd through

def try_except(cmd):
    try:
        cmd
    except:
        pass
0
Rosty Koryaha On

I use a different way, with a new variable:

continue_execution = True
try:
    command1
    continue_execution = False
except:
    pass
if continue_execution:
    try:
        command2
    except:
        command3

to add more commands you just have to add more expressions like this:

try:
    commandn
    continue_execution = False
except:
    pass
0
Seyit Hocuk On

Actually I think he wants the following in a nicer way:

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