How to Create Custom Exception in Python: Simple Guide
To create a custom exception in Python, define a new class that inherits from
Exception or one of its subclasses. Then, you can raise this custom exception using the raise keyword to signal specific error conditions in your code.Syntax
To create a custom exception, define a class that inherits from Exception. You can add an __init__ method to accept custom error messages or data.
- class CustomError(Exception): defines the new exception class.
- def __init__(self, message): initializes the error message.
- super().__init__(message) calls the base class constructor to set the message.
python
class CustomError(Exception): def __init__(self, message): super().__init__(message)
Example
This example shows how to define a custom exception and raise it when a condition is met. It also demonstrates catching the custom exception to handle it gracefully.
python
class NegativeNumberError(Exception): def __init__(self, message): super().__init__(message) def check_positive(number): if number < 0: raise NegativeNumberError(f"Negative number not allowed: {number}") return number try: check_positive(-5) except NegativeNumberError as e: print(f"Caught an error: {e}")
Output
Caught an error: Negative number not allowed: -5
Common Pitfalls
Common mistakes when creating custom exceptions include:
- Not inheriting from
Exceptionor its subclasses, which can cause unexpected behavior. - Failing to call
super().__init__()in the constructor, so the error message is not set properly. - Using bare
except:clauses that catch all exceptions, hiding your custom exceptions.
python
class BadError: pass # Missing inheritance from Exception class GoodError(Exception): def __init__(self, message): super().__init__(message) try: raise GoodError("This is a good custom error") except GoodError as e: print(e)
Output
This is a good custom error
Quick Reference
| Step | Description |
|---|---|
| Define class | Create a class inheriting from Exception |
| Add __init__ | Optionally add constructor to accept message |
| Call super() | Use super().__init__(message) to set error message |
| Raise exception | Use raise CustomException('message') to trigger |
| Catch exception | Use try-except to handle your custom exception |
Key Takeaways
Always inherit your custom exception class from Exception or its subclasses.
Use super().__init__(message) in your constructor to set the error message correctly.
Raise your custom exception with the raise keyword to signal errors.
Catch your custom exceptions specifically to handle them properly.
Avoid bare except clauses to prevent hiding your custom exceptions.