Exception handling
Madhavan Mukund
https://www.cmi.ac.in/~madhavan
Programming, Data Structures and Algorithms using Python
Week 1
When things go wrong
Our code could generate many types of errors
y = x/z, but z has value 0
y = int(s), but string s does not represent a valid integer
y = 5*x, but x does not have a value
y = l[i], but i is not a valid index for list l
Try to read from a file, but the file does not exist
Try to write to a file, but the disk is full
Madhavan Mukund Exception handling PDSA using Python Week 1 2/6
When things go wrong
Our code could generate many types of errors
y = x/z, but z has value 0
y = int(s), but string s does not represent a valid integer
y = 5*x, but x does not have a value
y = l[i], but i is not a valid index for list l
Try to read from a file, but the file does not exist
Try to write to a file, but the disk is full
Recovering gracefully
Try to anticipate errors
Provide a contingency plan
Exception handling
Madhavan Mukund Exception handling PDSA using Python Week 1 2/6
Types of errors
Python flags the type of each error
Madhavan Mukund Exception handling PDSA using Python Week 1 3/6
Types of errors
Python flags the type of each error
Most common error is a syntax error
SyntaxError: invalid syntax
Not much you can do!
Madhavan Mukund Exception handling PDSA using Python Week 1 3/6
Types of errors
Python flags the type of each error
Most common error is a syntax error
SyntaxError: invalid syntax
Not much you can do!
We are interested in errors when the code is running
Name used before value is defined
NameError: name ’x’ is not defined
Division by zero in arithmetic expression
ZeroDivisionError: division by zero
Invalid list index
IndexError: list assignment index out of range
Madhavan Mukund Exception handling PDSA using Python Week 1 3/6
Terminology
Raise an exception
Run time error → signal error type,
with diagnostic information
NameError: name ’x’ is not
defined
Handle an exception
Anticipate and take corrective action
based on error type
Unhandled exception aborts execution
Madhavan Mukund Exception handling PDSA using Python Week 1 4/6
Terminology
Handling exceptions
Raise an exception
Run time error → signal error type, try:
with diagnostic information ... ← Code where error may occur
NameError: name ’x’ is not
...
defined
except IndexError:
Handle an exception
... ← Handle IndexError
Anticipate and take corrective action
based on error type except (NameError,KeyError):
... ← Handle multiple exception types
Unhandled exception aborts execution
except:
... ← Handle all other exceptions
else:
... ← Execute if try runs without errors
Madhavan Mukund Exception handling PDSA using Python Week 1 4/6
Using exceptions “positively”
Collect scores in dictionary
scores = {"Shefali":[3,22],
"Harmanpreet":[200,3]}
Update the dictionary
Batter b already exists, append to list
scores[b].append(s)
New batter, create a fresh entry
scores[b] = [s]
Madhavan Mukund Exception handling PDSA using Python Week 1 5/6
Using exceptions “positively”
Traditional approach
Collect scores in dictionary
scores = {"Shefali":[3,22], if b in scores.keys():
"Harmanpreet":[200,3]} scores[b].append(s)
else:
Update the dictionary scores[b] = [s]
Batter b already exists, append to list
scores[b].append(s)
New batter, create a fresh entry
scores[b] = [s]
Madhavan Mukund Exception handling PDSA using Python Week 1 5/6
Using exceptions “positively”
Traditional approach
Collect scores in dictionary
scores = {"Shefali":[3,22], if b in scores.keys():
"Harmanpreet":[200,3]} scores[b].append(s)
else:
Update the dictionary scores[b] = [s]
Batter b already exists, append to list Using exceptions
scores[b].append(s)
try:
New batter, create a fresh entry scores[b].append(s)
except KeyError:
scores[b] = [s]
scores[b] = [s]
Madhavan Mukund Exception handling PDSA using Python Week 1 5/6
Flow of control
...
x = f(y,z)
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a)
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a) def g(m):
...
h(m)
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a) def g(m):
...
h(m) def h(s):
...
h(s)
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a) def g(m):
...
h(m) def h(s):
...
h(s)
IndexError not
handled in h()
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a) def g(m):
...
h(m) def h(s):
...
IndexError
h(s)
inherited from h()
IndexError not
handled in h()
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
def f(a,b):
...
g(a) def g(m):
...
IndexError
h(m) def h(s):
inherited from g()
...
IndexError
h(s)
inherited from h()
Not handled? IndexError not
handled in h()
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
IndexError
inherited from f() def f(a,b):
...
g(a) def g(m):
...
IndexError
h(m) def h(s):
inherited from g()
...
Not handled? IndexError
h(s)
inherited from h()
Not handled? IndexError not
handled in h()
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6
Flow of control
...
x = f(y,z)
IndexError
inherited from f() def f(a,b):
Not handled? ...
Abort! g(a) def g(m):
...
IndexError
h(m) def h(s):
inherited from g()
...
Not handled? IndexError
h(s)
inherited from h()
Not handled? IndexError not
handled in h()
Madhavan Mukund Exception handling PDSA using Python Week 1 6/6