[CentralOH] Changing Exception Raised
Mark Erbaugh
mark at microenh.com
Wed Oct 20 21:55:54 CEST 2010
I am developing some utility routines for parsing user input data. I would like all my routines to raise the same exception, i.e. ValueError, if the input data is invalid. In some cases, I can use routines already in the standard Python library. For example, decimal.Decimal() will take a string as input, so this is satisfactory to parse my input; however, decimal.Decimal() raises decimal.InvalidOperation if the string cannot be parsed. I could write code to catch the InvalidOperation exception and raise a ValueError, but I wonder if there is a better/more elegant way?
Mark
import decimal
def str_to_decimal(x):
"""
convert <str> do Decimal
x - <str> input
returns Decimal
raises ValueError if x is not valid format for Decimal
"""
try:
return decimal.Decimal(x)
except decimal.InvalidOperation:
raise ValueError
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20101020/4e9cc288/attachment.html>
More information about the CentralOH
mailing list