Python Error Handling Guide: Master try, except, finally

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

Error Handling in Python with try, except, finally

Handling errors is an essential part of building high-quality, reliable software. Even the most experienced developers are not immune to runtime errors. To prevent these situations from crashing your application, Python provides powerful tools for exception handling.

This guide covers the proper use of try, except, and finally blocks to write error-resistant code.

Python Exception Handling Basics

What Is Error Handling?

Error handling in Python lets you catch exceptions that occur during program execution. Instead of crashing the application, the system performs specific actions to gracefully handle the problem.

Key Components of the Exception Handling System

Python's error handling system is built on three main blocks:

  • try — the block of code where an exception may occur
  • except — the block that handles a specific error type
  • finally — the block that runs regardless of the outcome

Basic Structure of try-except-finally

Syntax of the Main Construct

try:
    # Code that may raise an exception
    pass
except SpecificError:
    # Code to handle the specific error
    pass
finally:
    # Code that always executes
    pass

Practical Example of the Basic Structure

try:
    user_input = input("Enter a number: ")
    number = int(user_input)
    print(f"You entered: {number}")
except ValueError:
    print("Error: please enter a valid number")
finally:
    print("Operation complete")

If the input is valid, the program prints the number. If invalid, an error message is shown. The finally block runs in both cases.

Handling Different Exception Types

Multiple Error Handling

Python allows you to handle different exception types using multiple except blocks:

try:
    dividend = 10
    divisor = 0
    result = dividend / divisor
except ZeroDivisionError:
    print("Division by zero is not allowed")
except ValueError:
    print("Invalid data format detected")
except TypeError:
    print("Incompatible data types for this operation")
finally:
    print("Math operation processing complete")

Error Handling Without a finally Block

The finally block is optional. Without it, the program handles the exception and continues execution:

try:
    data_list = [1, 2, 3, 4, 5]
    element = data_list[10]  # Attempting to access an out-of-range index
except IndexError:
    print("Attempted to access an index outside the list range")

Getting Detailed Exception Information

Using the as Keyword

To get detailed information about an exception, use the as keyword:

try:
    calculation = 15 / 0
except ZeroDivisionError as error:
    print(f"Error detected: {error}")
    print(f"Error type: {type(error).__name__}")

Output:

Error detected: division by zero
Error type: ZeroDivisionError

Catching All Exceptions

In some cases, you may want to catch any possible exception:

try:
    potentially_risky_operation()
except Exception as error:
    print(f"An error occurred: {error}")

Blogs

Book Recommendations