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
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.
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.
Yes, we can define one try block with multiple catch blocks in Java.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With