
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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!
- Related Articles
- How to pass argument to an Exception in Python?
- What is the correct way to pass an object with a custom exception in Python?
- How to handle an exception in Python?
- How to raise an exception in Python?
- How to pass a variable from Activity to Fragment in Android?
- How to pass a variable from BeforeTest to Test annotation in TestNG?
- How to pass a date variable in sql query in a JSP?
- How do I pass a variable to a MySQL script?
- How to ignore an exception and proceed in Python?
- How to pass a variable into a jQuery attribute-contains selector?
- How to capture an exception raised by a Python Regular expression?
- How to pass optional parameters to a function in Python?
- How to pass keyword parameters to a function in Python?
- How to declare a variable in Python?
- How to catch KeyError Exception in Python?

Advertisements