try-except, but still displaying 'TypeError'

Hi everyone,

I encountered a very strange Error-Message with one of my python-scripts:

#some code here
if rmb.positive:                #drop selected Object
    try:
        if ow['selected'] != 'None' and ow['selected'] != '':    #checking a Property
            selected = ow['selected']
            selected.removeParent()
    except:
        TypeError

Somehow the terminal still shows me this message:

Python script error - object ‘Hand_Grab.R’, controller ‘interaction#CONTR#2’:
Traceback (most recent call last):
File “interaction.py”, line 89, in <module>
if ow[‘selected’] != ‘None’ and ow[‘selected’] != ‘’:
TypeError: argument of type ‘NoneType’ is not iterable
Normally the try - except should stop the Error to be shown, but it doesn’t.:confused:

I’ve tried this with 2 versions - both display this Error

I’ll be pleased if somebody can help me.

Ah, I see. You put if ow[‘selected’] != ‘None’, but None is an actual type of object. It should be if ow[‘selected’] != None. However, it looks like there might be another problem… What is ow?

i have never seen


except:
         TypeError


probably


except TypeError:

 

could work.

Oh, yeah - it should be like sevi said, or alternatively

except:
           pass

if you don’t want to do anything should the try fail.

Thank you SolarLune, that solved the Problem.
I’ve just tested an 2.56 build, which did not print that message.
Seams like an API-Change

BTW ow is the owner of this script.

EDIT:
except:
TypeError
does function - I’ve used it several times this way

It don’t function but sort of…
except:
Catch all exceptions then
TypeError
is executed, Probably putting a ‘TypeError’ class object on the stack and the throwing it away. Using pass as a noop is a bit clearer :slight_smile:

@LaH
Thanks for that explanation. I was never to sure about using Exceptions.

I just realised that

if ow['selected'] != None

doesn’t function, since I’m checking a string Property.

Changed None back to ‘None’ and somehow it works without that error. I did not change anything else! Weird :confused:

Anyway, Thank you all for your help

You can do


value = own.get("propertyName")

as second parameter you can enter a default value. Without it the default is None.

or you do:


try:
  value = obj["propertyName"]
except KeyError:
  value = None

or if you only need to know that the property exist:


if "propertyName" in obj:
  yourStatements

When working with Exceptions/Errors it is recommended:

  • to specify the error type you expect (otherwise you will miss unexpected errors)
  • to surround only the statement where you expect the errror (otherwise you will miss unexpected errors at an other statement)

Another recommendation from PEP8 (just google it :wink: ):

rather than


# rather than 
if x == None:
  ...
# better use
if x is None:
  ...

I hope it helps
Monster