Saturday, September 28, 2019

python - About catching ANY exception



How can I write a try/except block that catches all exceptions?



Answer



You can but you probably shouldn't:



try:
do_something()
except:
print "Caught it!"


However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:




try:
f = open('myfile.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

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...