reducing if statements and error handling
Doug Fort
doug.fort at verizon.net
Tue Aug 21 09:35:42 EDT 2001
Jeff wrote:
> Another easy newbie question here... Suppose I have a method that
> accepts a string (called 'value') as an argument. I want the method
> to check to see if the contents of the string is all numbers. Here's
> my logic:
>
> def checkvalue(value):
> if value.isdigit():
> print 'success: ' + value + ' is a valid entry'
> return 1
> else:
> print 'error: ' + value + ' is NOT a valid entry'
> return -1
>
> Questions:
> 1) can I reduce this "if" logic down to one statement, perhaps using
> lambdas?
> 2) is there a recommended approach for throwing errors? In this case,
> I'd want to throw an error if the text is not a number and stop
> processing. Can I define a custom exception to do that? Should I
> catch the error in the logic that called the method and throw the
> exception there if the method returns a "-1", or should I throw the
> exception here?
>
> Thanks!
> Jeff
>
Instead of the whole checkvalue function, why not say
try:
number = int(value)
except ValueError, instance:
print instance
With regards to number 2), I find that when I use exceptions judiciously I
don't need to have functions return a 'success' value. You can define
custom exceptions easily. It's a good idea to derive them from Exception,
but not absolutely neccessary.
--
Doug Fort <dougfort at dougfort.net>
http://www.dougfort.net
______________________________________________________________________
Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com
With Seven Servers In California And Texas - The Worlds Uncensored News Source
More information about the Python-list
mailing list