Using the Try-Except-Finally design in Python to process exceptions and perform final actions.

онлайн тренажер по питону
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

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

What is try-except-finally in Python

The try-except-finally construct in Python is a fundamental tool for exception handling and program flow control. This design allows developers to create reliable applications that correctly handle errors and unforeseen situations.

The try block is exception protection

The try block contains code where an exception may occur. This block serves as a "protective shell" for potentially dangerous code:

try:
    # Code where an exception may occur
    result = 10/0
print("Operation completed successfully")
except ZeroDivisionError:
    # Handling the division by zero exception
print("Error: division by zero!")

The exception block - exception handling

The except block follows the try block and contains code for handling specific types of exceptions. Python supports several ways of writing the except block:

Handling a specific type of exception:

try:
    number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
    print("Error: incorrect number entered")
except ZeroDivisionError:
    print("Error: division by zero is impossible")

Handling multiple exceptions simultaneously:

try:
    result = 10 / int(input("Enter a number: "))
except (ValueError, ZeroDivisionError) as e:
    print(f"Error occurred: {e}")

Universal handling of all exceptions:

try:
    result = 10 / 0
except Exception as e:
    print(f"Exception occurred: {e}")

The finally block is guaranteed to be executed

The finally block contains code that is always executed, regardless of whether an exception has occurred or not. This block is critical for freeing up resources.:

try:
    file = open("example.txt", "r")
    data = file.read()
    print(data)
except FileNotFoundError:
    print("File not found!")
finally:
# This code will be executed anyway
    if 'file' in locals():
file.close()
print("File is closed")

else block - execution on success

The else block is executed only if there are no exceptions in the try block.:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero!")
else:
print(f"The operation was completed successfully. Result: {result}")
finally:
print("Operation completion")

The complete try-except-else-finally structure

try:
    # Main code
    file = open("data.txt", "r")
    content = file.read()
    result = len(content) / 10
except FileNotFoundError:
    print("File not found")
except ZeroDivisionError:
    print("Division by zero")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
print(f"File processed successfully. Result: {result}")
finally:
# Freeing up resources
    if 'file' in locals():
file.close()
print("Operation completed")

Best Usage Practices

1. Use the context manager for files:

try:
    with open("example.txt", "r") as file:
        data = file.read()
        print(data)
except FileNotFoundError:
    print("File not found!")
# The file will close automatically

2. Handle specific exceptions:

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    result = 100 / number
except ValueError:
    print("Error: no number entered")
except ZeroDivisionError:
    print("Error: division by zero")

3. Error logging:

import logging

try:
    risky_operation()
except Exception as e:
    logging.error(f"Error occurred: {e}")
raise # Raise the exception again

The order of block execution

  1. try - executed first
  2. except - is executed only when an exception occurs
  3. else - executed only if there was no exception
  4. finally - always executed last

Proper use of the try-except-finally construction makes the code more reliable, readable, and helps avoid program crashes when errors occur.

 

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base