CMPUT 175 Lecture #5
CMPUT 175 Lecture #5
Introduction to Foundations
of Computing
Exceptions and handling Errors
What if
the user enters a string instead of an integer?
We try to pop an empty stack?
we try to divide by zero?
We try to read from a file which doesn’t exist?
We try to access a remote location but the network is
down?
def foo():
try:
astring = 'hello'
astring[0] = 'j'
except TypeError:
raise # Using raise will raise the exception caught in the exception clause
main()
def foo():
try:
astring = 'hello'
astring[0] = 'j'
except TypeError:
raise TypeError('foo cannot handle this') # propagating to caller
main()
February 7, 2024 © Osmar R. Zaïane : University of Alberta 25
Exception Class
Most built-in exceptions are derived from the
Exception class. For example: ArithmeticError,
IndexError, NameError, ValueError, TypeError,
AssertionError etc. are all derived from the
Exception class.
All user defined exceptions should also be derived
from the Exception class.
In a try statement with an except clause that
mentions the Exception class, that clause
handles any exception classes that are derived
from the Exception class.
main()
class MyDB:
...
def addRecord(self, id, name):
assert type(id) is IntType, "id is not an integer: %r" % id
assert type(name) is StringType, "name is not a string: %r" % name
...