[CentralOH] Changing Exception Raised

Eric Floehr 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?
> 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
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20101020/5f44fe7d/attachment-0001.html>

More information about the CentralOH mailing list