Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How do you properly ignore Exceptions in Python?

I have a try-except block in following code and I just want to continue with the code by ignoring the exception block.

try:
    x,y =7,0
    z = x/y
except:
    #do nothing

The problem is if I leave the ‘except’ block empty or with a #do nothing, it gives an error as follows

File "C:/Users/~foo.py, line 7
IndentationError: expected an indented block.

How do I properly bypass the except block?      


1 Answer
Rajendra Dharmkar

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.