Advertisements
Advertisements
प्रश्न
Write a function called oops that explicitly raises a Index Error exception when called. Then write another function that calls oops inside a try/except statement to catch the error. What happens if you change oops to raise Key Error instead of Index Error?
मामले का अध्ययन
Advertisements
उत्तर
def oops():
raise IndexError("Index is out of range")
def call_oops():
try:
oops()
except IndexError as error:
print("Caught IndexError:", error)
call_oops()
Output:
Caught IndexError: Index is out of range
If oops() is changed to raise KeyError, the except IndexError block will not match it. The KeyError will remain unhandled and will propagate to the caller, usually terminating the program with a traceback. It can be caught by adding except KeyError or by catching a suitable common exception class.
shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
