Professional Documents
Culture Documents
Lecture 31
Lecture 31
Lecture 31
Lecture 31
Lecture Outline
• Exception handling
– CS1001 Lecture 31 –
Example: Raising exceptions
class Circle(GeometricObject):
def __init__(self, radius, color="red", filled=True):
super().__init__(color,filled)
self.setRadius(radius)
def getRadius(self):
return self.__radius
def getArea(self):
return math.pi*self.__radius**2
def getDiameter(self):
return 2*self.__radius
def getPerimeter(self):
return 2*math.pi*self.__radius
def printCircle(self):
print(self.__str__() + " radius: " + str(self.__radius))
– CS1001 Lecture 31 – 1
Accessing the exception object
try:
<body>
except ExceptionType as ex:
<handler>
• For example:
try:
c1 = Circle(-1)
print("c1’s area is",c1.getArea())
except RuntimeError as ex:
print("Invalid radius.",ex,end=" ")
Output:
– CS1001 Lecture 31 – 2
Exception handling advantages
– CS1001 Lecture 31 – 3
Chain of function calls
class Exception1(Exception):
def __init__(self):
print("Exception1 occurred")
class Exception2(Exception):
def __init__(self):
print("Exception2 occurred")
class Exception3(Exception):
def __init__(self):
print("Exception3 occurred")
def main():
try:
function1()
print("statement 1")
except Exception1:
print("exception handled in main")
print("statement 2")
– CS1001 Lecture 31 – 4
def function1():
try:
function2()
print("statement 3")
except Exception2:
print("exception handled in function1")
print("statement 4")
def function2():
try:
function3()
print("statement 5")
except Exception3:
print("exception handled in function2")
print("statement 6")
def function3():
# raise an Exception (1, 2, or 3)
main()
Exception3 occurred
exception handled in function2
statement 6
statement 3
statement 4
statement 1
statement 2
– CS1001 Lecture 31 – 5
• If we raise Exception2 in function3():
Exception2 occurred
exception handled in function1
statement 4
statement 1
statement 2
– CS1001 Lecture 31 – 6
else and finally
• Consider:
try:
<code-that-can-throw-an-OSError>
except OSError:
<handle-the-OSError>
else:
<more-code-that-can-throw-an-OSerror>
finally:
<clean-up-code>
– CS1001 Lecture 31 – 7
• The else provides a location where code is executed
only if there are no exceptions in the try body; it
is run before the finally block; and any exceptions
raised here are not caught here.
– CS1001 Lecture 31 – 8