inline exception handling in python

wheres pythonmonks wherespythonmonks at gmail.com
Thu Aug 12 14:25:25 EDT 2010


On Thu, Aug 12, 2010 at 2:19 PM, wheres pythonmonks
<wherespythonmonks at gmail.com> wrote:
> On Thu, Aug 12, 2010 at 2:08 PM, Thomas Jollans <thomas at jollybox.de> wrote:
>> On Thursday 12 August 2010, it occurred to wheres pythonmonks to exclaim:
>>> try:
>>>    f = n / d
>>> except:
>>>    f = float("nan")
>>
>> A catch-all except clause. Never a good idea. It's not as bad in this case, as
>> there is only one expression, but there are still a couple of other exceptions
>> that have a chance of occurring here: KeyboardInterrupt and SystemExit.
>> So:
>>
>> try:
>>    f = n / d
>> except ZeroDivisionError:
>>    f = float('nan')
>>
>>
>>> f = n / d except float("nan");
>>
>> So this syntax really isn't adequate for real use: catch-all except clauses
>> are frowned upon, and rightfully so.
>>
>> Besides, more often than not, you want to have a finally clause around when
>> you're dealing with exceptions.
>>
>>
>>> (Obviously, I am thinking about more complicated functions than "n/d"
>>> -- but this works as an example.)
>>
>> The more complex the function is, the more likely it is to raise an exception
>> you can't handle that easily.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
> With a bit imagination the syntax can handle specific exceptions:
>
> f = n /d except except(ZeroDivisionError) float("nan")
>
> f = n /d except except(ZeroDivisionError) float("nan")
> except(ValueError) float("nan")
>
> But then we cannot bind to useful variable you say...
>
> I think the problem in my case is best solved by look before you leap,
> or a wrapper function.  [I just hate function call overhead for this.
> ]
>
> Thanks,
>
> W
>

I mean something along these lines:

f = n /d  except(ZeroDivisionError) float("nan") except(ValueError) float("nan")



More information about the Python-list mailing list