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

How to pass a variable to an exception in Python?

I have created an exception class as follows

class ExampleException(Exception):
    pass

How can I give it a variable when it gets raised and then retrieve that variable when I handle it in the try-except block?


1 Answer
Manogna

Here we are passing a variable to given exception. We are defining a custom exception ExampleException which is a subclass of base class Exception and also defining the __init__ method. We use a try-except block to raise the exception and pass the variable to the exception as follows.

class ExampleException(Exception):
def __init__(self, foo):
self.foo = foo
try:
raise ExampleException("Bar!")
except ExampleException as e:
print e.foo

OUTPUT

"C:/Users/TutorialsPoint1/~bar.py"
Bar!

Advertisements

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