Question: (Python) Exercise-1: Raising Exceptions Try the following code one by one: raise NameError(Name not Found) raise IndexError(Sorry, index not found!) raise KeyError(Sorry, my fault!) What

(Python)

Exercise-1: Raising Exceptions

Try the following code one by one:

raise NameError(Name not Found)

raise IndexError("Sorry, index not found!")

raise KeyError("Sorry, my fault!")

What it does?

Exercise-2: Raising Exceptions

Try the following code:

try

:

raise

NameError(

'Name not found'

)

except

NameError:

print

(

'caught it'

)

What it does?

Exercise-3: Raising Exceptions using class

Here is an example related to RuntimeError. Here, a class is created that is a sub-class

from RuntimeError. This is useful when you need to display more specific information when an

exception is caught. In the try block, the user-defined exception is raised and caught in the except

block.

Try the following code:

class MyException(Exception):

pass

# MyException classinherits from the Exception class

raise MyException("Caught MyException")

What it does?

Now, add the try/finally block as shown below:

class MyException(Exception):

pass

# MyException classinherits from the Exception class

try:

raise MyException("Caught MyException")

finally:

print ("Done")

What it does?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!