Python: catch either one of two exceptions
本问题已经有最佳答案,请猛点这里访问。
我有以下代码。
1 2 3 4 5 | 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 |
我最近发现,我还需要考虑一个可能的
1 2 3 4 5 6 7 | 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 |
我不想要一个赤裸的
您可以在一行中捕获多个异常;
1 2 3 4 5 | final_dict["short_title"] = article_as_dict["short_title"] try: final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"] except (IndexError, KeyError) as e: final_dict["picture_url"] = None |
您可以在一行中捕获多种类型的错误。
从python文档:
An except clause may name multiple exceptions as a parenthesized tuple
像这样捕捉错误会更像Python: