How to better write multiple exceptions with redundant code in Python?
问题 How can I better write the following snippet in Python: try: statement-1 except Exception1: codeblock-1 codeblock-2 except Exception2: codeblock-2 Just to be clear, I want to execute two codeblocks when the first exception occurs, while only the latter of these two codeblocks when the second exception occurs. 回答1: You have two options, as I see it; either: Extract codeblock-2 into a function and just call it (you repeat only one line this way); or Catch both exceptions in the same except ,