Raising Custom Errors in Python show
Raising Custom Errors in Python
In Python, you can define your own exceptions by creating a new class that inherits from the built-in Exception
class. This is useful when you need to create specific error types that can provide more information about what went wrong in your code.
1. Defining a Custom Exception
To define a custom exception, create a new class that inherits from Exception
.
# Define a custom exception
class CustomError(Exception):
pass
2. Raising a Custom Exception
Use the raise
keyword to raise the custom exception.
# Raise a custom exception
raise CustomError("This is a custom error message")
3. Handling a Custom Exception
Use a try
block to catch and handle the custom exception.
# Handle a custom exception
try:
raise CustomError("This is a custom error message")
except CustomError as e:
print(e)
# Output:
# This is a custom error message
4. Adding Attributes to Custom Exceptions
You can add attributes to your custom exceptions to provide additional information about the error.
# Custom exception with attributes
class CustomError(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
super().__init__(message)
try:
raise CustomError("An error occurred", 500)
except CustomError as e:
print(e.message, "Error Code:", e.code)
# Output:
# An error occurred Error Code: 500
5. Using Custom Exceptions in Functions
Custom exceptions can be used in functions to signal specific error conditions.
# Function using custom exceptions
def check_positive(number):
if number < 0:
raise CustomError("Number must be positive", 400)
return number
try:
check_positive(-10)
except CustomError as e:
print(e.message, "Error Code:", e.code)
# Output:
# Number must be positive Error Code: 400