Use the pass
statement to use a try block without except in Python. A pass
is just a placeholder for nothing, it just passes along to prevent SyntaxErrors.
try:
doSomething()
except:
pass
The pass statement does nothing and it is used when a statement is required syntactically but the program requires no action.
Python try without except
Simple example code using try without except (ignoring exceptions) in Python.
my_list = []
try:
# ValueError
my_list.remove(1)
except:
# this runs
print(my_list)
pass
Output:
If you have to specify multiple exception classes, make sure to wrap them in parentheses.
If you’re confident that your block won’t raise an exception, you could just remove the try block altogether
for i in lines:
print(i[3])
How to properly ignore exceptions
try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt
, SystemExit
and stuff like that, which are derived directly from BaseException
, not Exception
.
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.