try:
list_one = eval(input))
list_two = eval(input()
sum = 0
newlis = []
for i in range(len(list_one))。
newlis.append(list_one[i] * list_two[i])
for i in newlis:
sum = i
print(sum)
except IndexError:
print("index out of bound")
except NameError:
print("該串列有一些非數字值")
如果我運行這段代碼,它要求逐一輸入兩個串列。我已經設定了一個例外,以防輸入任何非整數元素的串列。現在,如果我第一次輸入這個串列[1,b,2,4],錯誤立即出現了。我希望在我輸入這兩個串列后出現這個錯誤資訊。
uj5u.com熱心網友回復:
你可以簡單地做如下的操作:
try:
list_one, list_two = input(), input()
list_one, list_two = eval(list_one), eval(list_two)。
sum=0
newlis = []
for i in range(len(list_one))。
newlis.append(list_one[i] * list_two[i])
for i in newlis:
sum = i
print(sum)
except IndexError:
print("index out of bound")
except NameError:
print("該串列有一些非數字值")
但是請記住,這并不能阻止傳遞數字以外的任何東西,它只是阻止傳遞一個包含語法錯誤的元素(就像你在例子中做的那樣,因為a是無效的,但是"a"是有效的)。
所以你必須為TypeError添加一個except,并改變你的NameError的資訊:
try:
list_one, list_two = input(), input()
list_one, list_two = eval(list_one), eval(list_two)。
sum=0
newlis = []
for i in range(len(list_one))。
newlis.append(list_one[i] * list_two[i])
for i in newlis:
sum = i
print(sum)
except IndexError:
print("index out of bound")
except NameError:
print("The given object is invalid")
exceptTypeError。
print("傳遞的物件不是一個數字的串列")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320014.html
標籤:
上一篇:使用quiver繪制向量場
下一篇:.NET5遷移后的例外問題
