11. exception handling rocky k. c. chang october 18, 2015 (adapted from john zelle’s slides)

17
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Upload: jasmine-austin

Post on 19-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

11. EXCEPTION HANDLING

Rocky K. C. ChangOctober 18, 2015(Adapted from John Zelle’s slides)

Page 2: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Objectives• To understand the idea of exception handling and be able

to write simple exception handling code that catches standard Python run-time errors.

Page 3: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Exception Handling• Various error messages can occur when executing

Python programs. Such errors are called exceptions.• An exception is a value (object) that is raised (“thrown”)

signaling that an unexpected, or “exceptional,” situation has occurred.

• Python contains a predefined set of exceptions referred to as standard exceptions.

Page 4: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.1

Try•List = [1,2,3]; List[3]•file = open("unknown.py", "r")•x = 3 + "4"•in = 10•int("10.4")•import maths

Page 5: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Standard exceptions in Python

Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.

See https://docs.python.org/3/library/exceptions.html#bltin-exceptions for all built-in exceptions

Page 6: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.2

Find a Python file that has functions. Try to make an error inside the function and observe the error messages reported to you.

Page 7: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Propagation of Raised Exceptions

Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.

Page 8: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Propagation of Raised Exceptions• An exception is either handled by the client code, or

automatically propagated back to the client’s calling code, and so on, until handled.

• If an exception is thrown all the way back to the main module (and not handled), the program terminates displaying the details of the exception.

Page 9: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.3

Incur an error message from math.factorial(-1).Now try

try:math.factorial(-1)

except ValueError:print("Sorry, factorial()

does not admit negative number.")

Page 10: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Catching and Handling Exceptions• The try statement has the following form:try:

<body>except <ErrorType>:

<handler>• Exceptions are caught and handled in Python by use of a

try block and exception handler.• When Python encounters a try statement, it attempts to

execute the statements inside the body.• If there is no error, control passes to the next statement after the try … except.

• Else, Python looks for an except clause with a matching error type. If one is found, the handler code is executed.

Page 11: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.4Consider while True: number = eval(input("Enter a positive number: ")) if number >= 0:

break # Exit loop if number is valid

Use Try-Except block to catch the errors when the user is not entering a number. An error message will be printed out.

Page 12: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.5

Now we want to improve the codes for exercise 11.4. If a user is not entering a number, in additional to the error message, he will be prompted to enter a positive integer until he enters a positive number.

Page 13: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.6

Now we impose a range of numbers (say from 0 to 9, inclusive) acceptable to the program in Exercise 11.5.

Page 14: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.7Now you are given the function below:

def getNumber(): number = eval(input("Enter a number between 0 and 9, inclusive: ")) if number < 0 or number > 9: raise ValueError("The input must be between 0 and 9, inclusive.")

return number

Use this function to solve Exercise 11.6.

Page 15: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.8

If you have been using eval() all along, replace eval() with int(). Any difference between the error messages received here and those in the previous exercise?

Page 16: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

EXERCISE 11.9

Replace your except handler with

except ValueError as err_mesg:

print(err_mesg)

and use int(). Observe the difference.

Page 17: 11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

END