Error Handling (Exception Handling)

Python Lesson Seven: How to handle errors or exceptions in programs.

Learn Python

February 5, 2025

Error Handling (Exception Handling)

Lesson Seven: Error Handling (Exception Handling)

Welcome to the seventh lesson in our Python learning series! In this lesson, we will focus on how to handle errors or exceptions in programs. Error handling is a very important part of programming because it helps you control the behavior that occurs when unexpected problems arise during program execution.

 

1. What Are Exceptions?

When an error occurs during the execution of a Python program, an exception is raised. If this exception is not handled properly, the program stops running and displays an error message.

 

For example:

 
x = 10 / 0 # Error: Division by zero

If you run the code above, the following error will appear:

 
ZeroDivisionError: division by zero

Common Types of Exceptions

  • ZeroDivisionError : Occurs when attempting to divide by zero.
  • TypeError : Occurs when using incorrect data types.
  • ValueError : Occurs when passing an invalid value.
  • FileNotFoundError : Occurs when trying to open a non-existent file.
  • IndexError : Occurs when trying to access an index that doesn't exist in a list.
  • KeyError : Occurs when trying to access a key that doesn't exist in a dictionary.
 

2. How to Handle Errors Using try and except

To prevent the program from stopping when an error occurs, you can use the try and except structure. The code that might cause an error is placed inside the try block, and if an error occurs, the code inside the except block is executed.

 

A. Basic Syntax

 
try:
# Code that may cause an error
x = 10 / 0
except ZeroDivisionError:
# Code to execute if the error occurs
print("Cannot divide by zero!")

Note : If you want to handle all types of errors without specifying a particular type, you can use except alone.

 
try:
x = 10 / 0
except:
print("An error occurred!")

3. Handling Multiple Exceptions

You can handle more than one type of error using multiple except blocks.

 
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")

4. Using else and finally

A. else Block

The else block is used to execute code if no error occurs in the try block.

 
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")
else:
print(f"The result is: {result}")

B. finally Block

The finally block is used to execute code regardless of whether an error occurs or not. It's often used to close files or clean up resources.

 

5. Raising Exceptions Manually Using raise

You can also manually raise exceptions using the raise keyword. This is useful when you want to stop the program if certain conditions are not met.

 

6. Practical Applications

Application 1: Checking if a File Exists

 
import os


file_name = "example.txt"


try:
with open(file_name, "r") as file:
print(file.read())
except FileNotFoundError:
print(f"The file {file_name} does not exist!")

Application 2: Validating User Input

 
try:
num = int(input("Enter a number: "))
print(f"The number you entered is: {num}")
except ValueError:
print("Please enter a valid number!")

Application 3: Handling Errors in Lists

my_list = [1, 2, 3]


try:
print(my_list[5]) # Index out of range
except IndexError:
print("The index does not exist in the list!")
 

7. Tips for Handling Errors

  • Use try and except Carefully :
    Don't use try and except to avoid all errors. Only handle the errors you expect to occur.

  • Specify Exception Types :
    Always try to specify the exact type of exception instead of using a general except.

  • Use finally to Close Resources :
    If you're working with files or databases, use finally to ensure resources are closed even if an error occurs.

  • Raise Appropriate Errors :
    Use raise to throw custom errors when necessary.

 

Conclusion

In this lesson, you learned how to handle errors or exceptions in Python using try, except, else, and finally. These skills are essential for making your programs more robust and stable.

 

In the next lesson, we will discuss modules and how to use them to reuse and better organize your code. Keep practicing and don't hesitate to ask questions if you need help!

 

🚀 You're now on the right path to becoming a professional programmer!

Comments

No Comments

There are no comments

Please login to leave a review

  • Web development tutorial A-0

    Web development tutorial A-0

    From Zero to Hero: A Complete Web Development Journey

    View article
  • Differences Between Android and iOS

    Differences Between Android and iOS

    Mobile Application Development: Differences Between Android and iOS and Best Practices

    View article
  • Game Development with Unity

    Game Development with Unity

    Game Development with Unity: From Concept to Final Product

    View article
  • Mastering Programming with Python

    Mastering Programming with Python

    Mastering Programming with Python: Practical Projects and Tips

    View article
  • What are the benefits of websites

    What are the benefits of websites

    Benefits of websites for companies

    View article
  • Web development tutorial A-1

    Web development tutorial A-1

    Lesson 1: Learn HTML from Scratch - A Comprehensive Introduction with Tools Setup

    View article
  • Web development tutorial A-2

    Web development tutorial A-2

    Lesson Two: Learning HTML from Scratch - Advanced Tags and Tables

    View article
  • Artificial Intelligence Qwen AI

    Artificial Intelligence Qwen AI

    Qwen AI is a multi-functional AI model that supports languages and handles creative and interactive tasks

    View article