Lets say I have the following Python code:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
A problem might occur in line 3, when x.child_list is None. This obviously gives me a TypeError, saying that:
'NoneType' Object has no attribute '_____getitem_____'
What I want to do is, whenever x.child_list[0] gives a TypeError, simply ignore that line and go to the next line, which is "link = x.link"...
So I'm guessing something like this:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
Except TypeError:
# Pass, Ignore the statement that gives exception..
What should I put under the Except block? Or is there some other way to do this?
I know I can use If x.child_list is not None: ..., but my actual code is a lot more complicated, and I was wondering if there is a more pythonic way to do this
What you're thinking of is this:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
except TypeError:
pass
However, really it's best practice to put as little as possible in the try/catch
block:
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
pass
link = x.link
id = x.id
However, what you really should do here is avoid try/catch
entirely, and do something like this instead:
x = some_product()
name = x.name
first_child = x.child_list[0] if x.child_list else "no child list!"
# Or, something like this:
# first_child = x.child_list[0] if x.child_list else None
link = x.link
id = x.id
Your choice, of course, ultimately depends on your desired behavior--do you want to leave first_child
undefined or not, etc.
Since you only want to handle the exception on that line, only catch it there.
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
first_child = None
link = x.link
id = x.id
when you catch an exception you directly move out of the try scope, the better solution is to prevent the exception from occurring by modifying your code in that line to become:
if x.child_list[0] != None:
first_child = x.child_list[0]
hope this helps.
Edit
as you edited your question and you don't want this solution then the only way is to catch the exception right after that specific line:
try:
first_child = x.child_list[0]
except TypeError:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With