How to Handle Errors and Exceptions in Python

 

 

Introduction

When programming in Python, errors and exceptions are common, but they don’t always have to break your program. By properly handling errors, you can ensure that your program continues to run smoothly, even when something unexpected happens. Learning how to handle exceptions will make your Python code more robust and user-friendly.

Objective

The objective of this tutorial is to teach you the basics of error and exception handling in Python using the try, except, else, and finally blocks. We will also discuss how to create custom exceptions and use them to enhance your error management strategy.

Code Example


def divide_numbers(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("Error: Cannot divide by zero.")
    except TypeError:
        print("Error: Please provide numbers for division.")
    else:
        print(f"The result is: {result}")
    finally:
        print("Execution completed.")
        
# Test the function with different inputs
divide_numbers(10, 2)  # Normal case
divide_numbers(10, 0)  # Error case: division by zero
divide_numbers(10, 'a')  # Error case: invalid type

Explanation of Program Structure

In this Python code, we define a function divide_numbers(x, y) that attempts to divide two numbers:

  • try block: This is where we put the code that might cause an exception. In this case, we’re trying to perform the division operation.
  • except block: If an error occurs in the try block, Python looks for an except block that matches the error. We handle two types of errors here: ZeroDivisionError (if y is zero) and TypeError (if one of the inputs is not a number).
  • else block: This block runs if no exceptions are raised in the try block. Here, we print the result of the division.
  • finally block: This block runs regardless of whether an exception was raised or not. It’s a good place to include cleanup code, such as closing files or database connections.

How to Run the Program

To run this program:

  • Open a Python editor or IDE (like PyCharm, VS Code, or even IDLE).
  • Copy and paste the code into a new Python file (e.g., error_handling.py).
  • Save the file and run it.
  • Observe how the program handles different types of errors (e.g., division by zero or invalid types).
© 2025 Learn Programming. All Rights Reserved.

 

One Reply to “How to Handle Errors and Exceptions in Python”

Leave a Reply to To tài khon min phí Cancel reply

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