[CentralOH] Changing Exception Raised

Nick Albright nick.albright at gmail.com
Fri Oct 22 16:53:45 CEST 2010


You might also try capturing the exception in an variable and then passing
the string version of that to the constructor of the value error, so you can
pass as much info in as possible:

ie:

try:
    return decimal.Decimal(x)
except Exception, e:
    raise ValueError( str(e) )

Peace,
 -Nick

On Wed, Oct 20, 2010 at 4:22 PM, Eric Floehr <eric at intellovations.com>wrote:

> Mark,
>
> 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.
>
> -Eric
>
>
> 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
>>
>>
>
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
>


-- 
Please note that as of 1/20 I no longer have a land phone line, only my
cell.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20101022/6592ffdb/attachment.html>


More information about the CentralOH mailing list