20. Raising Custom Exceptions
Python allows you to create and raise your own exception classes. This improves clarity by signaling specific error conditions.
Defining a Custom Exception
class NegativeNumberError(Exception):
pass
def factorial(n):
if n < 0:
raise NegativeNumberError("Factorial is not defined for negative numbers")
result = 1
for i in range(1, n+1):
result *= i
return result
Practice Challenge
Write a function square_root(n) that raises a NegativeNumberError if n is negative.
Wrap-Up
- Custom exceptions make code descriptive and easier to debug.
- Inherit from
Exceptionfor user-defined errors.