How can I write a try
/except
block that catches all exceptions?
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
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