Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/Except error when using 'None'

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!

like image 329
huitlacoche Avatar asked May 09 '26 20:05

huitlacoche


1 Answers

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')        
like image 143
timgeb Avatar answered May 12 '26 11:05

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!