Exceptions and traceback#
Education objectives
as a user: don’t panic, read
block
trywith keywordsexceptandfinallykeyword
raise
Exceptions and try, except syntax#
Exceptions and errors are common in all codes. There is a good system to handle them in Python. Let’s first see the following code, which gives an error despite being syntactically correct:
letters = "abc"
i = 3
print(letters[i])
When these lines are executed, Python stops its execution and print a traceback:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-30-8df9cec1a0ec> in <module>()
1 letters = "abc"
2 i = 3
----> 3 print(letters[i])
IndexError: string index out of range
Handling exception:
letters = "abc"
i = 3
try:
print(letters[i])
except IndexError as e:
print(f"An IndexError has been raised and caught (message: '{e}')")
An IndexError has been raised and caught (message: 'string index out of range')
Warning
Never use just
except:
It means except BaseException, i.e. “except all errors and exceptions”. A user
Control-C is an exception (KeyboardInterrupt) so it would be caught and have no effect.
if you want to catch “all possible exceptions (but not KeyboardInterrupt)”, use instead
except Exception:
issubclass(KeyboardInterrupt, BaseException) is true but
issubclass(KeyboardInterrupt, Exception) is false so except Exception: does not catch
KeyboardInterrupt.
Yes, this might be the first time you encounter the builtin function issubclass and the
concept of hierarchy of exceptions.
We computed the average value of a list of numbers in a previous exercise. The following code seems innocuous
numbers = [1, 2]
avg0 = sum(numbers) / len(numbers)
Except in the edge case when you apply it to an empty list. try and except is a good
way to avoid errors in your code
numbers = []
try:
avg0 = sum(numbers) / len(numbers)
except ZeroDivisionError:
print("Cannot compute average of empty list")
Cannot compute average of empty list
Full syntax#
try:
...
except <exception1> as e1:
...
except <exception2> as e2:
...
else:
...
finally:
...
ArithmeticError
ZeroDivisionError
IndexError
KeyError
AttributeError
IOError
ImportError
NameError
SyntaxError
TypeError
Exercise 13
Place each element of this string in a list while trying to convert elements to floats (i.e. “hello” should raise an error that it cannot be represented as a float, 2 and 1.5 should become floats). Do it by catching errors.
str_variables = "hello 1.5 2"
the_list_you_should_get = ["hello", 1.5, 2.0]
Hints:
float("a")raise ValueError,the str
str_variableshould be split.
Solution to Exercise 13
split_list = []
for value in str_variables.split():
try:
value = float(value)
except ValueError:
print(value, "is not a number")
split_list.append(value)
print(split_list)
hello is not a number
['hello', 1.5, 2.0]