Sometimes, you want to create your own error messages that fit your program better. Extending built-in exceptions helps you make custom errors that act like normal errors but with your own touch.
Extending built-in exceptions in Python
class MyError(Exception): pass
You create a new error by making a class that uses a built-in error like Exception as a base.
The pass means the new error works just like the base error without extra changes.
class MyError(Exception): pass
class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
try: raise ValidationError('Invalid input', 400) except ValidationError as e: print(f'Error: {e}, Code: {e.code}')
This program defines a custom error called MyError. It raises this error with a message, then catches it and prints the message.
class MyError(Exception): def __init__(self, message): super().__init__(message) self.message = message try: raise MyError('Something went wrong!') except MyError as e: print(f'Caught an error: {e.message}')
Always inherit from Exception or its subclasses to make your custom errors work well with Python's error system.
You can add extra information or methods to your custom error to help explain the problem better.
Use custom errors to make your code easier to understand and debug.
Custom errors help you make your program's problems clearer.
Extend built-in exceptions by creating a new class that inherits from them.
You can add extra details to your errors to help with debugging and handling.