In Python, exceptions are events that disrupt the normal flow of a program. They can be raised for various reasons, such as invalid input or unexpected conditions. Raising exceptions is a crucial part of error handling, allowing developers to manage and respond to issues effectively. Below are three practical examples of raising exceptions in Python, providing clear contexts and use cases.
When developing applications, ensuring that user input meets certain criteria is essential. This example demonstrates how to raise an exception if the input does not conform to expected standards.
def get_age():
age = input("Please enter your age: ")
if not age.isdigit() or int(age) < 0:
raise ValueError("Age must be a positive integer.")
return int(age)
try:
user_age = get_age()
print(f"User age is: {user_age}")
except ValueError as ve:
print(ve)
ValueError
to indicate that the provided value is not valid.Division by zero is a common mathematical error that can terminate a program unexpectedly. This example shows how to raise an exception when a division by zero is attempted.
def divide_numbers(num1, num2):
if num2 == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return num1 / num2
try:
result = divide_numbers(10, 0)
print(f"Result: {result}")
except ZeroDivisionError as zde:
print(zde)
ZeroDivisionError
exception is a built-in Python exception that can be raised manually for clarity.When working with file operations, it’s crucial to handle potential errors, such as trying to access a file that does not exist. This example illustrates how to raise an exception in such a scenario.
import os
def read_file(file_path):
if not os.path.isfile(file_path):
raise FileNotFoundError(f"File '{file_path}' not found.")
with open(file_path, 'r') as file:
return file.read()
try:
content = read_file('nonexistent_file.txt')
print(content)
except FileNotFoundError as fnfe:
print(fnfe)
FileNotFoundError
is raised to indicate that the specified file could not be found, enhancing error traceability.