lib
lib

Reputation: 2956

Except block not catching exception in ipython notebook

When I try this simple example in my current Python environment (a ipython notebook cell) I am not able to catch TypeError exception:

a = (2,3)
try:
  a[0] = 0
except TypeError:
  print "catched expected error"
except Exception as ex:
  print type(ex), ex

I get:

<type 'exceptions.TypeError'> 'tuple' object does not support item assignment

When I try to run the same copy-pasted code in a different ipython notebook on the same computer I get the expected output: catched expected error.

I understand it has something to do with my current environment, but I have no idea where to start looking! I tried also another example with AttributeError and in that case the catch block works.

EDIT: When I tried:

   >>> print AttributeError
   <type 'exceptions.AttributeError'>
   >>> print TypeError
   <type 'exceptions.AttributeError'>

I remembered that earlier in the session I made an error, which renamed TypeError:

try:
    group.apply(np.round, axis=1) #group is a pandas group
except  AttributeError, TypeError : 
#it should have been except  (AttributeError, TypeError)
    print ex

which gave me:

 ('rint', u'occurred at index 54812')

Upvotes: 2

Views: 3500

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124258

This line is at fault here:

except  AttributeError, TypeError :

This means: catch exceptions of type AttributeError, and assign that exception to the name TypeError. In essence, you did this:

except AttributeError as e:
    TypeError = e  # instance of AttributeError!

You can rectify this with

del TypeError

so that Python finds the built-in type again.

The better solution is to use the correct syntax:

except (AttributeError, TypeError):

Because of how easy it is for that mistake to be made, Python 2.6 added the except .. as syntax, and the older syntax using except Exception, name: has been removed from Python 3 altogether.

Upvotes: 1

Andy Feely
Andy Feely

Reputation: 265

I think it may be that the TypeError has to be implicitly imported for some environments:

from exceptions import TypeError

Give that a go!

Upvotes: 3

Related Questions