Try/Except error when using 'None'

huitlacoche picture huitlacoche · Jul 8, 2014 · Viewed 11.2k times · Source

I have a bit of code that isn't behaving as expected. I've condensed it down to the problem here:

item = None

try:
    if item != None:
        print('pass')
except TypeError, e:
    print('fail')

if item is something other than 'None' type it prints pass. I wanted raise an exception if the item is None but when I set item to None nothing prints out.

I could easily do this with an if statement but I'm curious to know why this isn't working as an try/except.

any thoughts?

Thanks!

Answer

timgeb picture timgeb · Jul 8, 2014

There's nothing to raise a TypeError in your try block, it simply checks whether item !=None. item !=None will be True or False, but won't raise an error in either case.

You could do the following:

item = None
try:
    if item != None: # better: if item is not None
        print('pass')
    else:        
        raise TypeError 
except TypeError:
    print('fail')

Or simply:

item = None
if item != None: # better: if item is not None
    print('pass')
else:
    print('fail')