- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 implement user defined exception in Python?
We create user-defined or custom exceptions by creating a new exception class in Python. The idea is to derive the custom exception class from the exception class. Most built-in exceptions use the same idea to enforce their exceptions.
In the given code, you have created a user-defined exception class, the “CustomException“. It is using the Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the “raise” statement with an optional error message.
Let’s take an example.
In this example, we show how to raise a user-defined exception and catch errors in a program. Also, in the sample code, we ask the user to enter an alphabet again and again until he enters the stored alphabet only.
For help, the program provides a hint to the user so that he can figure out the correct alphabet.
#Python user-defined exceptions class CustomException(Exception): """Base class for other exceptions""" pass class PrecedingLetterError(CustomException): """Raised when the entered alphabet is smaller than the actual one""" pass class SucceedingLetterError(CustomException): """Raised when the entered alphabet is larger than the actual one""" pass # we need to guess this alphabet till we get it right alphabet = 'k' while True: try: foo = raw_input ( "Enter an alphabet: " ) if foo < alphabet: raise PrecedingLetterError elif foo > alphabet: raise SucceedingLetterError break except PrecedingLetterError: print("The entered alphabet is preceding one, try again!") print('') except SucceedingLetterError: print("The entered alphabet is succeeding one, try again!") print('') print("Congratulations! You guessed it correctly.")
- Related Articles
- How to create a user defined exception (custom exception) in java?
- User-defined Custom Exception in C#
- User-Defined Exceptions in Python
- When should we create a user-defined exception class in Java?
- User-defined Exceptions in Python with Examples
- How to create user defined exceptions in C#?
- How to implement a custom Python Exception with custom message?
- User Defined Literals in C++
- How to implement thread in user space?
- PHP User-defined functions
- How to display grant defined for a MySQL user?
- Using User-Defined Variables in MySQL
- How to create an unordered_map of user defined class in C++?
- Using TreeMap to sort User-defined Objects in Java
- What are user-defined exceptions in C#?
