Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 647
user4911943 Avatar asked Jun 15 '15 17:06

user4911943


People also ask

Can we have multiple try-except blocks in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you handle multiple exceptions with a single except clause?

You can also handle multiple exceptions using a single except clause by passing these exceptions to the clause as a tuple . except (ZeroDivisionError, ValueError, TypeError): print ( "Something has gone wrong.." ) Finally, you can also leave out the name of the exception after the except keyword.

Can we write more than 1 catch Bolcks with 1 try block?

Yes, we can define one try block with multiple catch blocks in Java.

Can you test for more than one error in one except line?

Yes, it is possible to check multiple error types with a single try and except statement. For the except , we can include multiple error types listed within a tuple. It will check if any of the listed errors are encountered.


1 Answers

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
like image 144
Colonel Thirty Two Avatar answered Sep 21 '22 23:09

Colonel Thirty Two