Junior
How to create a custom exception type in Python?
sobes.tech AI
Answer from AI
To create a custom exception, you need to inherit from the base class Exception (or one of its subclasses).
# Defining a custom exception
class MyCustomError(Exception):
# Override the __init__ method to add custom data
def __init__(self, message, error_code):
# Call the parent class constructor
super().__init__(message)
# Add custom attributes
self.error_code = error_code
# Override the __str__ method for a nice output
def __str__(self):
return f"Error #{self.error_code}: {self.args[0]}"
Example usage:
# Function that may raise our custom exception
def process_data(data):
if not isinstance(data, int):
raise MyCustomError("Invalid data type", 100)
if data < 0:
raise MyCustomError("Number must be be positive", 200)
return data * 2
# Handling the exception
try:
result = process_data("hello")
print(result)
except MyCustomError as e:
print(f"Caught custom exception: {e}")
print(f"Error code: {e.error_code}")
try:
result = process_data(-5)
print(result)
except MyCustomError as e:
print(f"Caught custom exception: {e}")
print(f"Error code: {e.error_code}")
try:
result = process_data(10)
print(result)
except MyCustomError as e:
print(f"Caught custom exception: {e}")
print(f"Error code: {e.error_code}")