You can use continue in Python try-except but ‘continue‘ is allowed within an ‘except‘ or ‘finally‘ only if the try block is in a loop. ‘continue‘ will cause the next iteration of the loop to start.
Python try except continue
A simple example code tries putting two or more functions in a list and using a loop to call your function.
def f():
print('Function f')
def g():
print('Function g')
funcs = [f, g]
for func in funcs:
try:
func()
except:
continue
Output:
How to continue for loop after exception?
Answer: After the first for-loop, add the try/except
. Then if an error is raised, it will continue with the next file.
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
pass
Source: https://stackoverflow.com/questions/18994334
How to ignore an exception and proceed?
Answer: The standard “nop” in Python is the pass
statement, Use this code.
try:
do_something()
except Exception:
pass
Using except Exception
instead of a bare except
avoid catching exceptions like SystemExit
, KeyboardInterrupt
etc.
Read: Python docs for the pass statement
Do comment if you have any doubts or suggestions on this Python exception-handling topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.