[Tutor] Building Starships -- object of type 'int' has no len()

Cameron Simpson cs at zip.com.au
Wed Aug 20 01:26:36 CEST 2014


On 19Aug2014 16:41, Terry--gmail <terry.kemmerer at gmail.com> wrote:
>The bare 'except' was a throw away. By bare 'except' I am assuming you mean without defining the type of error 'except' is to act upon?
>
>try:
>    something
>except ValueError:
>    do something
>
>-Or does bare 'except' mean something else?

You're right, it means "except" with no exception type.

The trouble with bare excepts is that they catch every exception, not just the 
one you expected to get. For example, this code:

   x = 1
   y = 2
   z = xx + y

would raise a NameError because "xx" is unknown. To my mind and yours it is 
just a typo, but in a dynamic language like Python this is only detected at 
runtime. If that code were inside a bare try/except then you might spent a very 
long time figuring out what was wrong because you're expecting one kind of 
failure be getting another.

As general practice, the rule of thumb is that you should make "except"s as 
precise as possible and only handle errors you explicitly expect and know what 
to do with.

An example from some of my code:

     try:
       arfp = open(arpath)
     except OSError as e:
       if e.errno == errno.ENOENT:
         arfp = None
       else:
         raise

Here I'm catching the expected possibility that the file I'm opening does not 
exist and setting arfp to None. Any other type of problem (permission denied, 
etc) continues on to raise an exception.

While this makes you code fragile in one sense, it prevents it _silently_ 
misinterpreting one thing as another, and that is usually best.

Cheers,
Cameron Simpson <cs at zip.com.au>

The aim of AI is to make computers act like the ones in the movies.
         - Graham Mann


More information about the Tutor mailing list