How to pass a variable to an exception in Python?


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.

Example

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!

Updated on: 13-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements