How can I write a try
/except
block that catches all exceptions?
Advertisement
Answer
You can but you probably shouldn’t:
JavaScript
x
5
1
try:
2
do_something()
3
except:
4
print("Caught it!")
5
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:
JavaScript
1
12
12
1
try:
2
f = open('myfile.txt')
3
s = f.readline()
4
i = int(s.strip())
5
except IOError as (errno, strerror):
6
print("I/O error({0}): {1}".format(errno, strerror))
7
except ValueError:
8
print("Could not convert data to an integer.")
9
except:
10
print("Unexpected error:", sys.exc_info()[0])
11
raise
12