Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Where do add an exception block

Posted by enquirer (enquirer), 24 January 2004
I've written a piece of code that prompts for input from the user, and I need to catch any non-numeric input he makes.  I can do by reading a test string and testing it with a Regular Expression, but shouldn't I be using an exception?  If so, do I just put all my code into a try block?

Posted by admin (Graham Ellis), 24 January 2004
Yes, you should be using an exception; it's Python's way of letting you trap errors in the environment in which your program is running (e.g. user input, file system, network failures) and also the ideal way of trapping functions that don't want to return a result but rather a warning / error.  For example, if you have a playing card object and want to return the suit, have the method raise an exception when asked about the suit of the joker.

Moving on to the second part of the code - no, don't just put a try around all your code.   A try / except pair is a conditional statement in a similar way to an if / else, and it's just as important to get the block ends right.  If you're making a number of inputs, you will have design decisions to make as to whether to

a) Put a series of try / except blocks sequentially after one another in the code (do this if you want to go on to each subsequent input even if the previous one has trapped)

b) Put all your inputs in a single try block (rarely recommended, but you could do this if you simpy want to error out if any of the inputs is in error)

c) Nest your try blocks (do this is you want to avoid any further input from your user once you hit a data error, but want to default values instead).

Here's an example of option (c):

Code:
try:
  val1 = input("Enter the value of your horse ")
  try:
     val2 = input("Enter the value of your car ")
  except:
     val2 = val1 + 100
except:
  print "oops .... "
  val1 = 50
  val2 = 150

print val1
print val2


If you enter nothing at all (just press enter to the first prompt), both inputs are defaulted.

If you enter one value, and just press enter for the second, the second value is defaulted to 100 greater than the first.

If you enter two values, they are assigned to val1 and val2.



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho