Raising Exceptions in Python: 3 Practical Examples

Explore three practical examples of raising exceptions in Python to enhance your error handling skills.
By Jamie

Understanding Raising Exceptions in Python

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.

Example 1: Validating User Input

Context

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)

Notes

  • This example uses ValueError to indicate that the provided value is not valid.
  • Variations could include additional checks, such as setting a maximum age limit.

Example 2: Handling Division by Zero

Context

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)

Notes

  • The ZeroDivisionError exception is a built-in Python exception that can be raised manually for clarity.
  • To enhance user experience, consider implementing a loop that prompts for new input until valid.

Example 3: File Not Found Error

Context

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)

Notes

  • The FileNotFoundError is raised to indicate that the specified file could not be found, enhancing error traceability.
  • You can also implement a fallback mechanism, such as creating a new file if it does not exist, depending on your application’s requirements.