Saturday 28 September 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...