如何在python中创建自定义错误处理?

时间:2016-11-28 19:09:44

标签: python error-handling python-3.5

i = 0
numbers = ["1","1","1","1","1"]
while 0 == 0:
   print(numbers[i])
   i+=1

一旦完成,就会说超出指数/范围。我怎么能说它用完了数字而不是错误?

我认为它被称为错误处理。

6 个答案:

答案 0 :(得分:1)

而不是while,我会使用for

numbers = ["1","1","1","1","1"]
for n in numbers:
  print(n)
print("ran out of numbers")

答案 1 :(得分:1)

堆栈跟踪告诉您要捕获的异常

>>> i = 0
>>> numbers = ["1","1","1","1","1"]
>>> while 0 == 0:
...    print(numbers[i])
...    i+=1
... 
1
1
1
1
1
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

所以添加一个try / except块

>>> i = 0
>>> numbers = ["1","1","1","1","1"]
>>> try:
...     while 0 == 0:
...         print(numbers[i])
...         i += 1
... except IndexError:
...     print("Ran out of numbers!")
... 
1
1
1
1
1
Ran out of numbers!

但请通过一些优秀的python教程。这将是一种学习语言的痛苦方法!

答案 2 :(得分:1)

您可以使用try和except

处理错误
try:
   print(numbers[i])
except Exception:
   print("ran out of numbers")

用您receiving

替换Exception

答案 3 :(得分:1)

在不修改代码的情况下,您可以raise a custom exception message然后break来避免无限循环:

i = 0
numbers = ["1","1","1","1","1"]
while 0 == 0:
   try:
      print(numbers[i])
      i+=1
   except IndexError:
      print('ran out of numbers')
      break

答案 4 :(得分:0)

您的循环条件始终为true,因此它会打印每个元素0-4,然后尝试打印不存在的第6个元素 - 因此超出索引/范围错误。 请尝试使用“for”循环。 Psuedocode:对于x的数字打印(数字[x])

答案 5 :(得分:0)

使用(546,1024,1024,2) 。您可以使用try..except

而不是0 == 0
True