[CentralOH] Changing Exception Raised
eric at intellovations.com
Wed Oct 20 22:22:49 CEST 2010
I think that way is pretty elegant. I don't know of a better way. Since
you don't care, you could just do a naked "except:" which will catch
everything and re-emit as a ValueError.
I get bit by Decimal a lot because for purity it doesn't accept floats. In
that case, a TypeError is raised.
On Wed, Oct 20, 2010 at 3:55 PM, Mark Erbaugh <mark at microenh.com> wrote:
> 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?
> 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
> return decimal.Decimal(x)
> except decimal.InvalidOperation:
> raise ValueError
> CentralOH mailing list
> CentralOH at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the CentralOH