Sometimes, you want to make your own special errors to explain problems clearly in your program.
Creating exception classes in Python
class MyError(Exception): pass
You create a new error by making a class that uses Exception as its base.
The pass means the new error acts like a normal error unless you add more code.
MyError.class MyError(Exception): pass
class ValueTooSmallError(Exception): def __init__(self, message): self.message = message def __str__(self): return f"ValueTooSmallError: {self.message}"
class NegativeNumberError(Exception): def __init__(self, number): self.number = number def __str__(self): return f"NegativeNumberError: {self.number} is not allowed"
This program makes a new error called MyError. It checks if a number is negative. If yes, it raises the error with a message. The try block runs the check. If the error happens, the except block catches it and prints the message.
class MyError(Exception): pass def check_number(x): if x < 0: raise MyError("Negative numbers are not allowed") else: print(f"{x} is okay") try: check_number(5) check_number(-3) except MyError as e: print(f"Caught an error: {e}")
You can add extra details to your error by adding methods or properties.
Use raise to create your error when a problem happens.
Catch your error with except YourErrorName as e to handle it nicely.
Create your own errors by making classes that inherit from Exception.
Use raise to trigger your custom error when needed.
Catch and handle your custom errors with try-except blocks.