In Python, By defining a new class that inherits from the built-in Exception class or one of its subclasses, you can define your own unique exceptions in Python. An illustration of how to define a user-defined exception in Python is as follows:
class CustomException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
In the example above, we define a custom exception called CustomException
that inherits from the base Exception
class. We also override the __init__
method to allow for passing a custom error message when creating an instance of the exception.
Here’s how you can use the custom exception in your code:
def divide_numbers(a, b):
if b == 0:
raise CustomException("Division by zero is not allowed.")
return a / b
try:
result = divide_numbers(10, 0)
print("Result:", result)
except CustomException as e:
print("An error occurred:", e.message)
In the above code, the divide_numbers
function checks if the divisor b
is zero. If it is, it raises a CustomException
with a custom error message. In the try-except
block, we catch the CustomException
and print the error message.
Output:
An error occurred: Division by zero is not allowed.
By defining and using custom exceptions, you can create more specific and meaningful error handling in your Python programs.