Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to implement a custom Python Exception with custom message?
In Python, you can create custom exceptions by inheriting from built-in exception classes. This allows you to define specific error types with meaningful messages for your application. Custom exceptions help make your code more readable and provide better error handling.
Creating a Custom Exception Class
To implement a custom Python exception with a custom message, you need to create a class that inherits from a built-in exception class like Exception, ValueError, or RuntimeError. The custom class should have an __init__ method to store the custom message.
Example
Here's how to create and use a custom exception with a custom message ?
class CustomValueError(ValueError):
def __init__(self, arg):
self.arg = arg
try:
a = int(input("Enter a number:"))
if not 1 < a < 10:
raise CustomValueError("Value must be within 1 and 10.")
except CustomValueError as e:
print("CustomValueError Exception!", e.arg)
The output of the above code is ?
Enter a number:45 CustomValueError Exception! Value must be within 1 and 10.
How It Works
In this example, CustomValueError inherits from ValueError. The __init__ method accepts an argument that serves as the custom error message. When the exception is raised using raise CustomValueError("message"), the message is stored in the arg attribute and can be accessed when catching the exception.
Conclusion
Custom exceptions in Python provide a clean way to handle specific error conditions in your applications. By inheriting from built-in exception classes and adding custom messages, you can create more informative and maintainable error handling code.
