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