How do you properly ignore Exceptions in Python?

PythonServer Side ProgrammingProgramming

This can be done by following codes

try:
x,y =7,0
z = x/y
except:
pass

OR

try:
x,y =7,0
z = x/y
except Exception:
pass


These codes bypass the exception in the try statement and ignore the except clause and don’t raise any exception.

The difference in the above codes is that the first one will also catch KeyboardInterrupt, SystemExit etc, which are derived directly from exceptions.BaseException, not exceptions.Exception.

It is known that the last thrown exception is remembered in Python, some of the objects involved in the exception-throwing statement are kept live until the next exception. We might want to do the following instead of just pass:

try:
x,y =7,0
z = x/y
except Exception:
sys.exc_clear()

This clears the last thrown exception

raja
Published on 06-Dec-2017 13:45:57
Advertisements