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:
(
'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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started