In this tutorial, you'll learn how to create custom exception classes by inheriting from Python's built-in Exception class. You'll also explore the raise statement for manually throwing exceptions and the assert statement for debugging purposes. Understanding these concepts will help you write more robust and maintainable code.
Custom exceptions allow you to define specific error types that are relevant to your application. This makes your code more readable and easier to debug, as it clearly communicates what went wrong in a particular context. By inheriting from the Exception class, you can extend the functionality of built-in exceptions and create tailored error handling mechanisms.
To create a custom exception, you simply define a new class that inherits from Python's Exception class. This allows you to add additional attributes or methods if needed.
Let's start by creating a simple custom exception for invalid user input.
1class InvalidInputError(Exception):2"""Custom exception for invalid user input."""3pass45# Raising the custom exception6try:7user_input = int(input("Enter a positive number: "))8if user_input <= 0:9raise InvalidInputError(f"{user_input} is not a positive number.")10except InvalidInputError as e:11print(e)
Enter a positive number: -5 -5 is not a positive number.
In this example, we define a custom exception class InvalidInputError that inherits from Exception. We then use the raise statement to throw this exception when the user input is not a positive number. The exception message is displayed in the except block.
You can also add attributes to your custom exceptions to provide more context about the error.
1class InvalidInputError(Exception):2"""Custom exception for invalid user input."""3def __init__(self, message, value):4super().__init__(message)5self.value = value67# Raising the custom exception with attributes8try:9user_input = int(input("Enter a positive number: "))10if user_input <= 0:11raise InvalidInputError(f"{user_input} is not a positive number.", user_input)12except InvalidInputError as e:13print(f"Caught an error: {e}. Value was {e.value}")
Enter a positive number: -10 Caught an error: -10 is not a positive number. Value was -10
Here, we extend the InvalidInputError class to include an additional attribute value, which stores the invalid input value. This can be useful for debugging or logging purposes.
raise StatementThe raise statement is used to manually throw an exception in your code. You can raise built-in exceptions or custom exceptions as needed.
Let's see how you can use the raise statement with a built-in exception.
1def divide_numbers(a, b):2if b == 0:3raise ZeroDivisionError("Cannot divide by zero.")4return a / b56try:7result = divide_numbers(10, 0)8except ZeroDivisionError as e:9print(e)
Cannot divide by zero.
In this example, the divide_numbers function raises a ZeroDivisionError when the divisor is zero. The error message is then caught and printed in the except block.
assert StatementThe assert statement is used for debugging purposes. It checks if a given condition is true, and if not, it raises an AssertionError. This can be helpful during development to ensure that certain assumptions about your code are correct.
assert StatementLet's use the assert statement to validate user input.
1def process_input(user_input):2assert isinstance(user_input, int), "Input must be an integer."3if user_input < 0:4raise ValueError("Negative numbers are not allowed.")5return f"Processed {user_input}"67try:8result = process_input(-5)9except AssertionError as e:10print(e)11except ValueError as e:12print(e)
Input must be an integer.
In this example, the assert statement checks if user_input is an integer. If not, it raises an AssertionError with a custom message. This helps catch bugs early in development.
Let's create a complete program that uses custom exceptions and the raise and assert statements to handle file operations safely.
1class FileReadError(Exception):2"""Custom exception for file read errors."""3pass45def read_file(file_path):6try:7with open(file_path, 'r') as file:8content = file.read()9assert len(content) > 0, "File is empty."10return content11except FileNotFoundError:12raise FileReadError(f"File not found: {file_path}")13except AssertionError as e:14raise FileReadError(str(e))1516try:17file_content = read_file("example.txt")18print(file_content)19except FileReadError as e:20print(e)
In this example, we define a custom exception FileReadError for handling file-related errors. The read_file function attempts to open and read a file. If the file is not found, it raises a FileReadError. If the file is empty, it also raises a FileReadError using an assert statement.
Exception to create custom error types that are specific to your application.raise to manually throw exceptions when needed.assert for debugging purposes to ensure assumptions about your code are correct.By using these techniques, you can write more robust and maintainable Python applications with clear error handling mechanisms.
In the next tutorial, we'll explore how to interact with MySQL databases in Python. You'll learn how to perform basic CRUD operations such as Create, Insert, Select, Update, and Delete. This will provide a solid foundation for working with relational databases in your Python projects.
Stay tuned!