
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to implement a custom Python Exception with custom message?
For the given code above the solution is as follows
Example
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)
Output
Enter a number:45 CustomValueError Exception! Value must be within 1 and 10. Process finished with exit code 0
- Related Articles
- How to create a user defined exception (custom exception) in java?
- How to throw custom exception in Kotlin?
- How to implement Python __lt__ __gt__ custom (overloaded) operators?
- How to create a custom unchecked exception in Java?
- C++ Program to Create Custom Exception
- Form required attribute with a custom validation message in HTML5
- How to implement custom JSON serialization with Gson in Java?
- How to implement custom events in jQuery?
- Throw Custom Exception in Kotlin
- How to implement a custom AlertDialog View in Android?
- How can we create a custom exception in Java?
- What is the correct way to pass an object with a custom exception in Python?
- How to print custom message instead of ErrorStackTrace in java?
- User-defined Custom Exception in C#
- how can I design custom toast message in Android?

Advertisements