Lecture 31

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Computer Science 1001

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 setRadius(self, radius):


if radius < 0:
raise RuntimeError("Negative radius.")
else:
self.__radius = 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

• The exception object can be accessed in the except


clause:

try:
<body>
except ExceptionType as ex:
<handler>

• Here, ex is a variable that has been assigned the


exception object.

• For example:

from CircleWithException import Circle

try:
c1 = Circle(-1)
print("c1’s area is",c1.getArea())
except RuntimeError as ex:
print("Invalid radius.",ex,end=" ")

Output:

Invalid radius. Negative radius.

– CS1001 Lecture 31 – 2
Exception handling advantages

• It allows us to deal with errors without aborting


execution.

• It separates the detection of an error from the


handling of the error.

• A function can raise an exception to its caller and


the caller can handle the exception.

• Often the called function does not know how an


error should be handled.

• Many library functions raise exceptions. We can


now use the try-except clause to handle these
exceptions.

– CS1001 Lecture 31 – 3
Chain of function calls

• Suppose we create our own exception types as


follows:

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")

• We can use these exceptions to illustrate what


happens in a chain of function calls:

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()

• If we raise Exception3 in function3():

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

• If we raise Exception1 in function3():


Exception1 occurred
exception handled in main
statement 2

• If we were to insert a finally clause in


function2():
finally:
print("finally clause of function2")

raising an Exception1 in function3() would


produce:
Exception1 occurred
finally clause of function2
exception handled in main
statement 2

we see that the finally clause is executed prior to


the return of function2().

– CS1001 Lecture 31 – 6
else and finally

• Why would we use else? Why not just put the


code from the else block in the try? Or after the
try?

• 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>

• Here, we ensure that any exceptions thrown by


<more-code-that-can-throw-an-OSError> are
not caught in the except block.

• Putting the else block code after the try will


result in it always being executed (not just when
no exceptions have been raised). It will also be
executed after finally in this case.

– 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

You might also like