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
Cannot List Ftp Directory Using Ftplib - But Ftp Client Works
Python Map Object Is Not Subscriptable
Why Can't I Change Only a Single Element in a Nested List in Python
Unicodeencodeerror: 'Ascii' Codec Can't Encode Character '\Xe9' - -When Using Urlib.Request Python3
Using a Where _ in _ Statement
Trouble Installing Textblob with Pip
How to Ssh Connect Through Python Paramiko with Ppk Public Key
How to Plot and Annotate Grouped Bars in Seaborn/Matplotlib
Python Pyqt Signals Are Not Always Working
I am Sending Commands Through Serial Port in Python But They Are Sent Multiple Times Instead of One
Pandas Reading CSV as String Type
Smtplib Sends Blank Message If the Message Contain Certain Characters
Python 3 Replacement for Deprecated Compiler.Ast Flatten Function
Iterating Through Two Lists in Django Templates
Selenium Unable to Locate Element Only When Using Headless Chrome (Python)