Exception Handling Practices / Patterns

Terry Reedy tjreedy at udel.edu
Sat Aug 24 15:57:55 EDT 2013


On 8/24/2013 6:27 AM, Steven D'Aprano wrote:
> On Fri, 23 Aug 2013 22:25:55 -0700, snarf wrote:
>
> [...]
>> * Seems like exception handing within Classes is largely avoided and is
>> typically only used when calling external libraries.
>
> There is certainly no rule "avoid exceptions inside classes". Methods
> often raise exceptions to signal an error, e.g.:
>
> "My string".index("spam")

The rule only makes sense if it referring to try: except: in top-level 
class code, outside of def statements. Even then, it is wrong.

...
> # Worst
> except:
>
> Don't use the last one, except maybe in the interactive interpreter,

Stick with never. "except:" means the same thing as "except 
BaseException:", except that the latter indicates a deliberate choice 
rather than an indication of carelessness or laziness.

A bare except: is a disservice to the next maintainer of the code.

> since it will catch *everything*, even exceptions that probably shouldn't
> be caught like KeyboardInterrupt.

In Idle, when you type 'expression(' and hesitate, Idle tries to 
evaluate 'expression' to a function, behind the scenes, in order to 
provide a calltip with the function signature. Any error in 
'eval(expression)' should be caught and ignored so the user can continue 
typing.

This is one place where the original authors were too specific. They 
only caught NameError and AttributeError, when those were not the only 
possible eval errors in practice. The result was that people would 
occasionally type '(' and see idle quit.

idlelib .py files have about 20 bare 'except:'s, which I will try to 
fill out when I have reviewed the try part and understand what should be 
caught. It would be easier for me to read the code if the original 
authors had added their best guess as to what should be expected and caught.

-- 
Terry Jan Reedy




More information about the Python-list mailing list