Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Try/Catch: simply go to next statement when Exception

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

like image 742
user2436815 Avatar asked Mar 29 '14 20:03

user2436815


3 Answers

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.

like image 83
jdotjdot Avatar answered Sep 22 '22 11:09

jdotjdot


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
like image 44
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 11:09

Ignacio Vazquez-Abrams


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
like image 35
Ammar Avatar answered Sep 21 '22 11:09

Ammar