[Tutor] exceptions
Lloyd Kvam
pythontutor@venix.com
Sat, 13 Apr 2002 22:40:21 -0400
Here is the "check value" code for numeric input in my current project.
All values that are set from the user interface funnel through here. I
pulled out the numeric part because I think it is a reasonably complete
example for catching errors. Part of the process is to build a string
with useful information when something goes wrong to provide some context
in describing the error - as opposed to simply reporting "Invalid Value!"
def uicheckSet(self, fieldname, value):
''' Raise an exception for invalid value for this fieldname
'''
process = self.uigetProcess( fieldname) # i keep dictionary of processing info for each fieldname
... # skipping to numeric section
elif process in ['ui_integer', 'ui_money', 'ui_percent', 'ui_year']:
if not value: # value may not have come directly from user typing
value = 0 # so we "rationalize" it
value = str( value).strip()
if process == 'ui_money': regexp = '[-]?[0-9]*\.?[0-9]?[0-9]?'
elif process == 'ui_percent': regexp = '[-]?[0]*[.][0-9]+'
else: regexp = '[-]?[0-9]+'
try:
m = re.match( regexp, value)
if not m:
msg = "Invalid characters for field: %s. Received: %s. Valid set is: %s" % (fieldname,value,regexp)
raise ValueError, msg
elif m.group() != value:
msg = "Invalid character %s. Valid charaters: %s" % (value[m.end()],regexp)
raise ValueError, msg
except re.error, diag:
raise ValueError, str(diag)
else:
if process == 'ui_integer': value = int(value)
else: value = float(value)
range = self.uigetInput( fieldname) # here i get the valid range for this fieldname
if not range[0] <= value <= range[1]:
raise ValueError, '%s should be between %s and %s' % (fieldname, str(range[0]), str(range[1]))
After this, the fieldname will be set to the supplied value, and if all goes
well, stored in the database.
Cameron Stoner wrote:
> Hi all,
>
>
>
> How do you approach error trapping and use exceptions in Python to take
> care of it? How do you for all the possible dumb user mistakes? I mean
> give me the kind of thought process of how I should go about thinking
> this through in planning my program.
>
>
>
> Thanks guys for your help,
>
>
>
> Cameron Stoner
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582