Python: Multiple try except blocks in one?

一世执手 提交于 2020-07-08 12:47:23

问题


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


回答1:


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



回答2:


Unless I completely misunderstand you, this should do it:

try:
  thing1
  thing2
  thing3
except:
  pass

A try block can contain as many statements as you want.




回答3:


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.



回答4:


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



回答5:


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

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


来源:https://stackoverflow.com/questions/30851243/python-multiple-try-except-blocks-in-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!