Raising a Custom Exception
To raise a custom exception, use the raise keyword followed by an instance of your custom exception.
def divide(a, b):
if b == 0:
raise MyCustomError("Division by zero is not allowed", 400)
return a / b
Here the divide method raises the ‘MyCustomError’ when an attempt to divide by zero is made.
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the program’s instructions. When an error occurs, Python raises an exception, which can be caught and handled using try
and except
blocks. Here’s a simple example of handling a built-in exception:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
In this example, ZeroDivisionError
is a built-in exception that gets raised when you attempt to divide by zero.
Contact Us