- 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
What is the correct way to pass an object with a custom exception in Python?
In given code, a custom exception FooException has been created which is a subclass of the super class Exception. We will pass a string object to the custom exception as follows
Example
#foobar.py class FooException(Exception): def __init__(self, text, *args): super ( FooException, self ).__init__ ( text, *args ) self.text = text try: bar = input("Enter a string:") if not isinstance(bar, basestring): raise FooException(bar) except FooException as r: print 'there is an error' else: print type(bar) print bar
If this script is run at the terminal as follows we get
$ python foobar.py
We get the following if we enter a string
Output
"C:/Users/TutorialsPoint1/~foobar.py" Enter a string:'voila' <type 'str'> Voila
Advertisements