Main Content

What are exceptions - Python based answer

Archive - Originally posted on "The Horse's Mouth" - 2008-11-08 06:51:36 - Graham Ellis

How do you check for run time errors in your program? You'll include tests with if statements in almost every program you write, to ensure that user entered data is reasonable / as you would expect ... but you will also need to do more that that. You'll need to check whether a system function has run correctly - "Did that file open" type questions. One very commonly used approach to error checking of this sort is to call functions that return a special value (a cardinal value) in the event of an error - something that can never be a correct answer - and check for that value after every call. You'll see that approach used very widely indeed, especially in older languages.

But there's an alternative - the exception. With exceptions, you write code in a block that says "try" to perform a particular task, and if something goes wrong an exception is thrown and the code jumps to an exception / error recovery block. What are the advantages of exceptions:

a) There's no need to use cardinal values that may turn out to be not so improssible in the normal run of events anyway

b) You don't have to program for every possible error individually - you can lay out a safety net to catch any errors that occur within a certain area of the code irrespective of what they are

c) You have a need mechanism for correcting and bringing the code back together rather than having to code with lower level if tests.

Here's an example in Python. For clarity and completeness, in this program we raise the exception ourselves in the howlarge function rather than allowing the built in function called list to do so:

def howlarge(mylist):
   if isinstance(mylist,list):
      size = len(mylist)
   else:
      raise TypeError,"Only works on lists"
   return size


The main code for this short example is a single try block, in which we call the howlarge function multiple times. It will fail on the fourth of five calls, since the function traps any calls in which the object passed to it is not a llist - so you get three sets of results followed by an error message. You'll notice that if an exception is thrown, the code jumps to an appropriate handler and the rest of the try block is skipped.

try:
   print (howlarge([5,6,5,6,7]))
   print (howlarge([5,6,7]))
   print (howlarge([]))
   print (howlarge(14))
   print (howlarge([5,6,7]))
except StandardError,e:
   print "Oh - never mind ...."
   print e
print "Program Completed"


Once the except block has been completed (or the try block completed if no exception was thrown), the code runs from the end of the structure - in this case simply stating "Program Completed"

Dorothy:slee_liv grahamellis$ python oy
5
3
0
Oh - never mind ....
Only works on lists
Program Completed
Dorothy:slee_liv grahamellis$


Full source here. You'll find more on exceptions in Python, exceptions in C++, exceptions in Ruby and exceptions in Java here.