Python Raising Exceptions

Introduction

In Python, you can raise exceptions using the raise keyword. This allows you to create custom error messages and manage the flow of your program more effectively. Raising exceptions is useful when you want to indicate that an error has occurred in your program and provide specific error information to handle it appropriately.

Key Concepts

  • Raising Exceptions: Use the raise keyword to generate an exception.
  • Exception Types: Use built-in exception types or create custom exception classes.
  • Custom Messages: Provide custom error messages when raising exceptions.

Basic Syntax

raise ExceptionType("Custom error message")

Example

def divide(a, b):
    if b == 0:
        raise ValueError("The divisor cannot be zero.")
    return a / b

try:
    result = divide(10, 0)
except ValueError as e:
    print(e)

Output

The divisor cannot be zero.

Raising Built-in Exceptions

You can raise built-in exceptions to indicate specific error conditions.

Example: Raising a ValueError

def calculate_square_root(x):
    if x < 0:
        raise ValueError("Cannot calculate the square root of a negative number.")
    return x ** 0.5

try:
    result = calculate_square_root(-4)
except ValueError as e:
    print(e)

Output

Cannot calculate the square root of a negative number.

Example: Raising a TypeError

def add_numbers(a, b):
    if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
        raise TypeError("Both arguments must be numbers.")
    return a + b

try:
    result = add_numbers(10, "five")
except TypeError as e:
    print(e)

Output

Both arguments must be numbers.

Custom Exceptions

You can create custom exception classes by inheriting from the built-in Exception class. This allows you to define specific error conditions for your application.

Example: Creating and Raising a Custom Exception

class NegativeNumberError(Exception):
    def __init__(self, value):
        self.value = value
        super().__init__(f"Negative number error: {value} is not allowed.")

def process_number(n):
    if n < 0:
        raise NegativeNumberError(n)
    return n * 2

try:
    result = process_number(-10)
except NegativeNumberError as e:
    print(e)

Output

Negative number error: -10 is not allowed.

Raising Exceptions with Custom Messages

You can provide custom messages when raising exceptions to give more context about the error.

Example

def check_age(age):
    if age < 18:
        raise ValueError("Age must be at least 18.")
    return "Access granted."

try:
    result = check_age(16)
except ValueError as e:
    print(e)

Output

Age must be at least 18.

Real-World Example: User Input Validation

Raising exceptions can be useful for validating user input in applications.

Example

def get_user_age():
    age = input("Enter your age: ")
    if not age.isdigit():
        raise ValueError("Age must be a number.")
    age = int(age)
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    age = get_user_age()
    print(f"Your age is {age}.")
except ValueError as e:
    print(f"Invalid input: {e}")

Output (if user inputs a negative number)

Enter your age: -5
Invalid input: Age cannot be negative.

Output (if user inputs a non-numeric value)

Enter your age: abc
Invalid input: Age must be a number.

Conclusion

Raising exceptions in Python allows you to manage errors and unexpected conditions in your program effectively. By using the raise keyword, you can generate exceptions with custom messages, use built-in exception types, or create custom exception classes to handle specific error conditions. Understanding how to raise and handle exceptions is crucial for writing robust and maintainable Python code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top