What is the correct way to pass an object with a custom exception in Python?


In given code, a custom exception FooException has been created which is a subclass of the super class Exception. We will pass a string object to the custom exception as follows

Example

#foobar.py
class FooException(Exception):
def __init__(self, text, *args):
super ( FooException, self ).__init__ ( text, *args )
self.text = text
try:
bar = input("Enter a string:")
if not isinstance(bar, basestring):
raise FooException(bar)
except FooException as r:
print 'there is an error'
else:      
print type(bar)
print bar

If this script is run at the terminal as follows we get

$ python foobar.py

We get the following if we enter a string

Output

"C:/Users/TutorialsPoint1/~foobar.py"
Enter a string:'voila'
<type 'str'>
Voila


Updated on: 13-Feb-2020

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements