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 can I write a try/except block that catches all Python exceptions?

For the following code

    f = open('file.txt')
    s = f.readline()
    i = int(s.strip())

how do I write a try/except block that catches all exceptions?


1 Answer
Manogna

It is a general thumb rule that though you can catch all exceptions using code like below, you shouldn’t:

try:
    #do_something()
except:
    print "Exception Caught!"

However, this will also catch exceptions like KeyboardInterrupt we may not be interested in. Unless you re-raise the exception right away – we will not be able to catch the exceptions:

try:
    f = open('file.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

We get output like the following, if the file.txt is not available in the same folder as the script.

I/O error(2): No such file or directory
Advertisements

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