简体   繁体   English

不断捕获python中的异常

[英]Continually catch exception in python

I need to keep catching an exception while indexing a list throws a IndexError exception, for example: 在索引列表引发IndexError异常时,我需要不断捕获异常,例如:

l = []
while((l[3]) throws IndexError):
    //Add more data to the list
    l += [3]

How can I keep checking to see if the method call has thrown an exception without having nested a nested try/catch block? 如何在不嵌套嵌套的try / catch块的情况下继续检查方法调用是否引发了异常?

It depends what you would like to extend your list with. 这取决于您想要扩展列表的范围。 Assuming 'None' you could do it like this: 假设“无”,您可以这样做:

l = []
while True:
  try:
    l[3] = 'item'
    break
  except IndexError:
    l.extend([None])

print l # [None, None, None, 'item']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM