Chapter: Internet & World Wide Web HOW TO PROGRAM - Python

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Exception Handling - Python

In an interpreted language such as Python, errors pose a unique problem, because many errors caught at compilation time for a compiled language are not caught until run time in an interpreted language.

Exception Handling

 

In an interpreted language such as Python, errors pose a unique problem, because many errors caught at compilation time for a compiled language are not caught until run time in an interpreted language. These errors cause exceptions in Python. When a program encounters an exception, the program exits and displays an error message.

 

Exception handling enables programs and programmers to identify an error when it occurs and to take appropriate action. Exception handling is geared to situations in which a code block that detects an error is unable to deal with that error. Such a block of code will raise an exception. The programmer can write code that then catches the exception and handles the error in a “graceful” manner.

Python accomplishes exception handling through the use of try/except blocks. Any code that causes an error raises an exception. If this code is contained in a try block, the corresponding except block then catches the exception (i.e., handles the error). The core Python language defines a hierarchy of exceptions. A Python except block can catch one of these exceptions, or a subset of these exceptions, or it can specify none of these exceptions, in which case the code block catches all exceptions. Figure 28.14 shows how dividing a number by zero raises a ZeroDivisionError exception.

 

Figure 28.15 presents a simple program that illustrates exception handling in Python. The program requests two numbers from the user, then attempts to divide the first number by the second.

 

 

Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information.

>>> 1 / 0

 

Traceback (most recent call last): File "<stdin>", line 1, in ?

ZeroDivisionError: integer division or modulo by zero

>>> 

 

 

Fig. 28.14  Interactive session illustrating a ZeroDivisionError exception.

 

    # Fig. 28.15: fig28_15.py

    # A simple program that illustrates exceptions.

 

    def getFloat():

    return float( raw_input( "Enter a number: " ) )

 

7   number1 = number2 = None

 

8

    while number1 == None:

      try:

      number1 = getFloat()

      except ValueError:

      print "Value entered was not a number"

 

      while number2 == None:

      try:

      number2 = getFloat()

      except ValueError:

      print "Value entered was not a number"

 

      try:

      result = number1 / number2

      except ZeroDivisionError:

      print "Cannot divide by zero!"

      else:

print "The result of division is: %f" % result

Fig. 28.15  Demonstrating exception handling.

 

Lines 4–5 define function getFloat, which prompts the user for a number and returns the number that the user enters. This function gets user input through Python func-tion raw_input and then obtains the user-entered value as a floating-point value with Python function float.

 

Line 7 creates two variables (number1 and number2) and assigns None to both. Lines 9–19 use while loops to store user-entered values in these variables by using func-tion getFloat, with exception handling. In lines 9 and 15, we use the keyword is to test if the program has received a valid number. Lines 10–11 define a try block. Any code in the try block that raises an exception will be “caught” and handled in the corresponding except block (lines 12–13). The try block calls function getFloat to get the user input.

 

If the user does not enter a numerical value at the prompt, the float function raises a ValueError exception, which is caught by the except block (lines 12–13). This block prints an appropriate message before program control returns to the top of the while loop. Lines 15–19 repeat the same action to get a floating-point value for variable number2.

 

Lines 21-26 print the results of dividing variables number1 and number2. We place the call to divideNumbers in the try block. As we saw in Fig. 28.14, if a program attempts to divide by zero, the program raises a ZeroDivisionError. The except block in lines 26–27 catches this exception and prints an appropriate message to the screen.

 

A try block may optionally specify a corresponding else block (lines 25–26). If the code in the try block does not raise an exception, the program executes the code in the else block. If an exception is raised in the try block, the else block is not executed. In our example, the else block prints the result of the division.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.