How to raise custom exceptions in Python
To throw a custom exception, you can follow these steps:
- Firstly, create a new custom exception class that inherits from the built-in Exception class. Additional properties or methods can be added according to your needs.
class MyException(Exception):
pass
- to increase or elevate
raise MyException("This is a custom exception.")
The complete sample code is as follows:
class MyException(Exception):
pass
def divide(a, b):
if b == 0:
raise MyException("Division by zero is not allowed.")
return a / b
try:
result = divide(10, 0)
except MyException as e:
print(e)
The output is:
Division by zero is not allowed.
In this example, a custom exception class instance MyException is thrown and the exception information is printed when the divisor b is 0.