English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Python has manyBuilt-in exceptions, which will force your program to output errors when some errors occur.
However, sometimes you may need to create custom exception handling that meets your purposes.
In Python, users can define such exceptions by creating new classes. The exception class must derive directly or indirectly from the Exception class. Most built-in exceptions also derive from this class.
>>> class CustomError(Exception): ... pass ... >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError("An error occurred") Traceback (most recent call last): ... __main__.CustomError: An error occurred
Here, we create a user-defined exception named CustomError, which is derived from the Exception class. Like other exceptions, this new exception can be raised using a raise statement with an optional error message.
When we develop large Python programs, it is best to place all user-defined exceptions raised by the program in a separate file. Many standard modules can do this. They define exceptions as exceptions.py or errors.py separately.
User-defined exception classes can perform all operations that ordinary classes can, but we usually make them simple and clear. Most implementations declare a custom base class and derive other exception classes from it. The following example will make this concept clearer.
In this example, we will explain how to use user-defined exceptions to raise and catch errors in a program.
This program will prompt the user to enter a number until they correctly guess the stored number. To help them understand, it will indicate whether their guess is greater or less than the stored number.
# Define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Triggered when the input value is too small""" pass class ValueTooLargeError(Error): """Triggered when the input value is too large""" pass # Our main program # The user guesses a number until he/She guesses it right # You need to guess this number number = 10 while True: try: i_num = int(input("Enter a number: ")) if i_num < number: raise ValueTooSmallError elif i_num > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, please try again!") print() except ValueTooLargeError: print("This value is too large, please try again!") print() print("Congratulations! You guessed it right.")
This is an example run of the program.
Enter a number: 12 This value is too large, please try again! Enter a number: 0 This value is too small, please try again! Enter a number: 9 This value is too small, please try again! Enter a number: 10 Congratulations! You guessed it right.
Here, we define a base class named Error.
Our program actually raises two other exceptions (ValueTooSmallError and ValueTooLargeError) derived from this class. This is the standard method for defining user-defined exceptions in Python programming, but you are not limited to this method.
Visit this page for detailed informationHow to handle exceptions in Python.