मराठी

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.

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५८]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 8 Exception Handling & Generate Functions
EXERCISE | Q 11. | पृष्ठ १५८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×