inline exception handling in python

Thomas Jollans thomas at jollybox.de
Thu Aug 12 14:08:01 EDT 2010


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.



More information about the Python-list mailing list