myList = [1, 2, 3, 4]
try:
user_index_num = int(input(' Enter a number here: '))
value = int(input(' Enter an element here: '))
except Exception:
raise
except IndexError:
raise
if not 0 <= user_index_num <= len(myList)-1:
raise IndexError(f'Index {user_index_num} list assignment index out of range')
myList.insert(user_index_num, value)
print(myList)
需要滿足以下要求,但似乎無法實作。
如果程式的輸入是
15
3
程式的輸出是
Index 15 Error list assignment index out of range
例子:
如果程式的輸入是
3
T
程式的輸出是
Input Exception: invalid literal for int() with base 10: 'T'
uj5u.com熱心網友回復:
這就是你想要做的嗎?
myList = [1, 2, 3, 4]
index = -1
try:
index = int(input(' Enter an index here: '))
value = int(input(' Enter a value here: '))
if 0 < index < len(myList):
myList.insert(index, value)
else:
raise IndexError
except ValueError:
print('You need to enter valid numbers!')
except IndexError:
print(f'Index {index} out of range for list of values')
print(myList)
IndexError如果提供了超出現有范圍的索引myList(否則,它.insert()只會捕捉到最接近的值),這會引發一個。
它還捕獲兩種型別的例外,因為在相關例外之前沒有捕獲更廣泛的例外(如在您的示例中, whereexcept Exception會阻止其他例外在其之后被捕獲)。
如果您的觀點是您不想明確指定ValueError,而是想捕獲所有這些,則可以使用以下方法:
myList = [1, 2, 3, 4]
index = -1
try:
index = int(input(' Enter an index here: '))
value = int(input(' Enter a value here: '))
if 0 < index < len(myList):
myList.insert(index, value)
else:
raise IndexError
except IndexError:
print(f'Index {index} out of range for list of values')
except Exception as e:
print(e)
print(myList)
執行仍然繼續,因為通用例外被捕獲e并顯示,沒有未捕獲的例外結束程式。注意如何一般Exception被捉住后更具體IndexError。
最后,請注意 thatindex被設定為一個值以避免出現int()或 input()以某種方式引發 an 的情況IndexError,在這種情況下index,列印時將沒有值,引發另一個例外,這將再次終止您的程式。這似乎很愚蠢:畢竟,什么時候會int()或input()曾經提出IndexError? 但是 Python 沒有直接的方法來知道可能會引發什么例外,因此如果您沒有index事先設定為 -1 之類的值,您的 IDE 可能會向您發出警告。
(編輯:將默認值更改為index-1,以獲得一個實際上無效的值并且可以在例外處理代碼中檢查)
您提到您需要在捕獲錯誤后停止執行。有兩種好方法可以解決這個問題。如果您發現錯誤并在終止之前只希望為用戶提供一條友好的訊息,您應該以exit(1)(或其他一些非零數字)結束程式,以便啟動您的程式的人可以知道某些事情沒有結束 - 您可以使用不同的代碼表示不同的問題)。
except ValueError:
print('You need to enter valid numbers!')
exit(1)
或者,也許您的代碼是從其他一些代碼呼叫的,并且在自己捕獲錯誤并列印訊息后,您希望該代碼能夠再次捕獲它:
except ValueError:
print('You need to enter valid numbers!')
raise
這會重新引發已捕獲的錯誤。通常,只允許未捕獲的例外結束程式是不好的做法 - 例外的全部意義在于它應該是……一個例外。
uj5u.com熱心網友回復:
我稍微編輯了您的建議如下。
myList = [1, 2, 3, 4] index = -1 try:
index = int(input())
value = int(input())
if 0 < index < len(myList):
myList.insert(index, value)
print(myList)
else:
raise IndexError except IndexError:
print(f'Index {index} Error list assignment index out of range') except Exception as e:
print('Input Exception:', e)
我很確定這就是我的導師正在尋找的......
只剩下 20 次了,哈哈……謝謝你的幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366280.html
標籤:Python
上一篇:if陳述句,來回
