[英]I need to throw an user-defined error while there is no value for the entered key in the dict
在鍵沒有值但未調用except
塊時創建異常。
class NoElementError(Exception):
def __init__(self):
print("No element for this key")
data = { 1 : "vishnu" ,
2 : "Murshid" ,
3 : "vaseem" ,
4 : "abdu" ,
5 : "farooq" }
key = int(input("Enter key"))
try:
data.get(key,NoElementError)
except NoElementError as e:
print("Error",e)
未調用except
塊。
您可能會發現此模式更有用。 在此示例中,我們嘗試訪問硬編碼(丟失)密鑰
class NoElementException(Exception):
def __init__(self):
super().__init__('Missing key')
data = { 1 : "vishnu" ,
2 : "Murshid" ,
3 : "vaseem" ,
4 : "abdu" ,
5 : "farooq" }
try:
try:
print(data[99])
except KeyError:
raise NoElementException
except Exception as e:
print(e)
Output:
Missing key
或者:
try:
if 99 in data:
print(data[99])
else:
raise NoElementException
except Exception as e:
print(e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.