How to pass a variable to an exception in Python?

PythonServer Side ProgrammingProgramming

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!

raja
Published on 07-Dec-2017 10:34:20
Advertisements