Catch Exception and Continue Try Block in Python

Catch exception and continue try block in Python

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

how to continue for loop after exception?

Your own answer is still wrong on quite a few points...

import logging
logger = logging.getLogger(__name__)

def do_connect(self):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
# this one has to go outside the try/except block
# else `client` might not be defined.
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host['ip'], port=int(host['port']), username=host['user'], timeout=2)

# you only want to catch specific exceptions here
except paramiko.SSHException as e:
# this will log the full error message and traceback
logger.exception("failed to connect to %(ip)s:%(port)s (user %(user)s)", host)

continue
# here you want a `else` clause not a `finally`
# (`finally` is _always_ executed)
else:
self.connections.append(client)

How to continue a loop after catching exception in try ... except

As suggested by @JonClements what solved my problem was to use error_bad_lines=False in the pd.read_csv so it just skipped that lines causing trouble and let me execute the rest of the for loop.

python: try/except/else and continue statement

The tutorial gives a good start, but is not the language reference. Read the reference here.

Note in particular:

The optional else clause is executed if and when control flows off the end of the try clause.

clarified by footnote 2:

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

So your use of continue is explicitly addressed by that.

How to continue with next line in a Python's try block?

Take bar() out of the try block:

try:
foo()
except:
pass
bar()

Btw., watch out with catch-all except clauses. Prefer to selectively catch the exceptions that you know you can handle/ignore.



Related Topics



Leave a reply



Submit