English

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

Question

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?

Case Study
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 8: Exception Handling & Generate Functions - EXERCISE [Page 158]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 8 Exception Handling & Generate Functions
EXERCISE | Q 11. | Page 158
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×