OOP » Exceptions »

 

Exceptions

Object Composition Table Of Contents Builtin Functions
In many programming languages, exceptions are events which can be triggered and handled during program execution. They you to break the normal flow of execution in order to handle specific events such as errors or exceptions. The language provides some mechanism for both raising and handling exceptions during program execution.

an exception and handle thhandling exceptions so your program can take counter measures to deal with the specific event. If the exception is not handled, the program will abort with a runtime error.

Catching Exceptions

A classic use of exceptions is in dealing with run-time errors. For example, if you attempt to access a list element that is out of range, Python raises the IndexError exception. In the following code segment

myList = [ 12, 50, 5, 17 ]
print myList[ 4 ]
 

we attempt to print the item of the list at element $4$. But the legal range of indices is [0..3]. In this case, Python will automatically raise a specific exception to flag an error.

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range

By default, the exception causes the program to abort. To prevent this from happening, we can catch the exception and take counter measures such as printing a warning message.

try:
  myList = [ 12, 50, 5, 17 ]
  print myList[ 4 ]

except IndexError:
  print "Error: Index out of range."
 

How It Works

The try block encloses the group of statements for which you want to catch exceptions. It must be followed by one or more except blocks. Exception handling works as follows:

  • The statements within the try block are executed as normal.
  • If no exception is raised during the execution of that statement block, the except block is skipped.
  • If an exception is raised, the rest of the block is skipped. The type of exception is compared to that specified with the except statement. If it matches, the except block is executed and execution continues after the try block.
  • If an exception is raised and there is no matching except block, the exception is passed up to outer try blocks. If no matching except blocks are found, it becomes an unhandled exception and the program terminates with a message similar to that shown earlier.

Exception handlers are very useful when extracting user input.

while True:
  try:
     value = int(raw_input("Enter an integer value: "))
     break

  except ValueError:
     print "Oops!  That was not an integer.  Try again..."
 

Multiple Except Blocks

A try block can contain multiple except blocks.

try:
  x = 0
  myList = [ 12, 50, 5, 17 ]
  print myList[ 3 ] / x

except IndexError:
  print "Error: Index out of range."

except ZeroDivisionError:
  print "Error: Attempt to divide by zero."
 

In this case, we’ve added an exception handler to also catch divisions by zero. Without the handler, the program would abort since our program is incorrect and we are attempting to divide by zero. The last except block can omit the exception type in order to catch any exception.

try:
  x = 0
  myList = [ 12, 50, 5, 17 ]
  print myList[ 3 ] / x

except IndexError:
  print "Error: Index out of range."

except ZeroDivisionError:
  print "Error: Attempt to divide by zero."

except:
  print "Error: An exception was raised."
 

In some instances we may want to abort the program any way, even if we catch the exception. By catching the exception first, we can abort cleanly to clean up any loose ends. For example, if we have an output file opened, we may want to close it before the program aborts so the buffer is flushed.

Handlers at Different Scopes

The try blocks can be used at any position within a program. When an exception is raised, it is passed up to an earlier try block if it is not handled by a local try block.

def average( valueList ) :
   total = 0
   for x in valueList :
      total = total + x

   try:
      avg = total / len( valueList )
      return avg

   except ZeroDivisionError:
      return 0.0

myList = [ 12, 50, 5, None, 17 ]
try:
  listAvg = average( myList )
  print "The average = ", listAvg

except TypeError:
  print "An invalid type was in the list."
 

Python defines a number of built-in exceptions that can be raised automatically during program execution:

Raising Exceptions

We have seen several instances when Python automatically raises exceptions during program execution. But you can also raise an exception within your program

def min( value1, value2 ) :
   if value1 == None or value2 == None :
      raise TypeError
   if value1 < value2 :
      return value1
   else:
      return value2
 

Python also defines the assert statement which can be used to make assertions within your program. This is very useful for debugging programs.

def average( valueList ) :
   total = 0
   assert len( valueList ) > 0, "Empty list in average()."
   for x in valueList :
      total = total + x

   try:
      avg = total / len( valueList )
      return avg
 

If the test

len( valueList ) > 0
 

fails, an AssertionError is raised. The string argument is passed as an argument to the exception object. The prototype of the assert statement is

assert <test>, <data>

where the <data> part is optional.



Object Composition Table Of Contents Builtin Functions

© 2006 - 2008: Rance Necaise - Page last modified on September 30, 2006, at 06:15 PM