Python Error Handling: Try-Except-Finally Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Python Exception Handling: The Complete Guide

Errors are an inevitable part of software development. Even the most carefully written code can encounter unexpected situations: a missing file, division by zero, network connection issues, and more. To prevent your program from crashing in these scenarios, Python provides a powerful exception handling mechanism built around the try-except-finally construct.

How Does the try-except-finally Construct Work in Python?

The try-except-finally construct allows you to catch exceptions that occur during program execution and respond to them appropriately.

General Syntax:

try:
    # Code that might raise an exception
except SomeException:
    # Exception handling code
finally:
    # Code that always executes

How Each Block Works:

  • try: This block contains the main code where an exception might potentially occur.
  • except: Here you specify what to do if an exception is raised in the try block. You can specify a specific exception type (SomeException) to catch.
  • finally: The finally block always executes, regardless of whether an exception was raised in the try block. It is typically used to release resources, such as closing files, network connections, or database connections.

Example of Using try-except-finally

try:
    number = int(input("Enter an integer: "))
    result = 10 / number
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
except ValueError:
    print("Error: Please enter a valid integer.")
finally:
    print("Program finished.")

How This Code Works:

  1. The program asks the user to enter an integer.
  2. If the user enters 0, a ZeroDivisionError is raised, and the corresponding except block runs.
  3. If the user enters a non-integer value, a ValueError is raised, and the corresponding except block runs.
  4. The finally block always executes, printing a message that the program has finished.

Why Do You Need the finally Block?

The finally block guarantees that important code runs regardless of whether an exception occurred. Here are some common use cases:

  • Closing Files:

    file = open("data.txt", "r")
    try:
        content = file.read()
        # Process file content
    finally:
        file.close()  # Guaranteed file closure
    
  • Releasing Resources: Free up network connections, database connections, and other resources that must be closed or released after use.

  • Completing Logging or Cleaning Up Temporary Data: Use the finally block to finish writing to a log file or delete temporary files created during program execution.

Handling Multiple Exceptions

A single try block can raise several different types of exceptions. Python offers several ways to handle this situation:

Using Multiple except Blocks

try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(resu                

Blogs

Book Recommendations