Home > Back-end >  I need to throw an user-defined error while there is no value for the entered key in the dict
I need to throw an user-defined error while there is no value for the entered key in the dict

Time:01-25

The Exception is being created while there is no value for the key but except block is not invoked.

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)

The except block not called.

CodePudding user response:

You might find this pattern more useful. In this example we try to access a hard-coded (missing) key

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

Or:

try:
    if 99 in data:
        print(data[99])
    else:
        raise NoElementException
except Exception as e:
    print(e)
  • Related