Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have created a blank exception class as follows

class FooException(Exception):
    pass

How can I pass an object to the custom exception?


1 Answer
Manogna

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

#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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.