- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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!
Advertisements