如果发生特定类型的异常,则执行其他代码

时间:2020-07-12 12:26:17

标签: python

仅当发生IndexError时,我才想在其中执行其他代码:

try:
   execute code if no error
except IndexError:
   execute code 1
   execute code 2
except: #any other except type
   execute code 1

我不想在两个异常中两次键入相同的代码(代码1)

1 个答案:

答案 0 :(得分:0)

编写用于执行代码1的函数如何?

def execute_code_1():
    #wirte code here