Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: catch either one of two exceptions [duplicate]

I have the following piece of code. article_as_dict is a dictionary that I'm receiving from an external source:

final_dict["short_title"] = article_as_dict["short_title"]
try:
    final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"]
except IndexError:
    final_dict["picture_url"] = None

I discovered recently that I also need to account for a possible KeyError, is the block below the most pythonic way to do this?

final_dict["short_title"] = article_as_dict["short_title"]
try:
    final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"]
except IndexError:
    final_dict["picture_url"] = None
except KeyError:
    final_dict["picture_url"] = None    

I don't want a naked except clause because it's bad practice.

like image 932
zerohedge Avatar asked Dec 03 '25 09:12

zerohedge


1 Answers

You can catch multiple types of errors in one line.

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple

It would be more pythonic to catch your errors like so:

except (IndexError, KeyError)...

like image 148
Daniel Ong Avatar answered Dec 05 '25 23:12

Daniel Ong