Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

2.7 Exception Handling

Sometimes things go wrong in a program and it is out of your control. For instance, if the user does not enter the proper input an error may occur in your program. Python includes exception handling so programmers can handle errors like this. Generally, if there is a possibility something could go wrong you should probably use some exception handling. To use exception handling you write a try-except statement.

< statements before try except > try :

< try block statements > except [ Exception ]:

< except block statements >

< statements after the try except code >

A try-except block may monitor for any exception or just a certain exception. There are many possible exceptions that might be caught. For instance, a ValueError exception occurs when you try to convert an invalid value to an integer. A ZeroDivisionError exception occurs when you try to divide by zero. In the general form shown above, the Exception is optional. That's what the square brackets (i.e. [ ]) mean. You don't actually write the square brackets. They mean the exception is optional in this case. If the exception is omitted then any exception is caught.

Exception handling can be used to check user input for validity. It can also be used internally in the program to catch calculations that might result in an error depending on the values involved in the calculation. When a try block is executed if a run-time error occurs that the try-except block is monitoring then program control immediately skips to the beginning of the except block. If no error occurs while executing the try block then control skips the except block and continues with the statement following the try-except statement. If an error occurs and the except block is executed, then when the except block finishes executing control goes to the next statement after the try-except statement (Fig. 2.10).

Example 2.12 Here is a bulletproof version of the program first presented in Example 2.10. This example does not use short-circuit logic. It uses exception handling instead. Notice the use of exit(0) below. This is a Python function that exits the program immediately, skipping anything that comes after it.

1 t r y :

2 top = i n t ( i n p u t ("Please enter the numerator:"))

3 e x c e p t ValueError: # This try -except catches only ValueErrors

4 p r i n t ("You didn 't enter an integer.")

5 exit (0)

6

7 t r y :

8 bottom = i n t ( i n p u t ("Please enter the denominator:"))

9 e x c e p t : # This try -except catches any exception

10 p r i n t ("You didn 't enter an integer.")

11 exit (0)

12

13 t r y :

14 i f top % bottom == 0:

15 p r i n t ("The numerator is evenly divided by the" +

16 "denominator.")

17 e l s e :

18 p r i n t ("The fraction is not a whole number.")

19 e x c e p t ZeroDivisionError:

20 p r i n t ("The denominator cannot be 0.")

Fig. 2.10 Try-except statement

Try-except statements are useful when either reading input from the user or when using data that was read earlier in the program. Example 2.12 uses three try-except statements. The first two catch any non-integer input that might be provided. The last catches a division by zero error.

Practice 2.8 Add exception handling to the program in practice Problem 2.6so that if the user answers something other than their age that the programprints “You did not enter your age correctly”.

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel