Exception handling - comp
Download
Report
Transcript Exception handling - comp
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.
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.
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
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
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.
Propagation of Raised Exceptions
Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.
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.
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.")
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.
EXERCISE 11.4
Consider
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.
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.
EXERCISE 11.6
Now we impose a range of numbers (say
from 0 to 9, inclusive) acceptable to the
program in Exercise 11.5.
EXERCISE 11.7
Now 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.
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?
EXERCISE 11.9
Replace your except handler with
except ValueError as err_mesg:
print(err_mesg)
and use int(). Observe the difference.
END