Raising Exceptions in Python
Let’s go step by step to understand how to raise exceptions in Python, why we use it, and with practical examples.
What Does “Raising an Exception” Mean?
When we raise an exception, we explicitly tell Python: Stop execution here because something invalid or unexpected happened.
Why Raise Exceptions?
- To stop incorrect program execution.
- To validate user input.
- To enforce business logic rules.
- To prevent bad data in ML pipelines.
Key Idea
Instead of waiting for Python to crash naturally, we manually trigger an error using the raise keyword.
Basic Syntax of raise
raise ExceptionType("Custom error message") Example: Built-in Exception (Without raise)
Python
def divide(a, b):
return a / b
# Catching built-in exception
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print("Error occurred:", e)
else:
print("Result:", result) If we run the above code, we will see the output:
Output
Error occurred: division by zero
In the above example, Python automatically raises the built-in ZeroDivisionError, which we handle in the except block.
Example: Raising Exceptions in a Function
Python
def divide(a, b):
# Check if denominator is zero
if b == 0:
raise ZeroDivisionError("Denominator cannot be zero!")
return a / b
# Example usage
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print("Error occurred:", e)
else:
print("Result:", result) Output:
Output
Error occurred: Denominator cannot be zero!
Here, we manually raised the exception with a custom error message, which makes debugging more meaningful and user-friendly.
Raising Exceptions with if Statements
Sometimes we need to raise exceptions based on our own business logic, even if Python does not consider it an error.
Example: Check the age input.
Python
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
elif age < 18:
raise PermissionError("You must be 18 or older.")
else:
print("You are eligible.") Output Example:
Output
ValueError: Age cannot be negative!
In this example, Python allows negative numbers, but logically an age cannot be negative. So we manually raise a ValueError to enforce our business rule.