How to Use Try and Except in Python: Step by Step Guide

DJC > Tutorials

| Python |

In Python, error handling is essential to create robust programs and prevent them from stopping unexpectedly. To do this, the try and except structure is used.

In this tutorial, you will learn how to use try and except in Python effectively, with practical examples and best practices.


What Are Try and Except in Python?

try and except are control structures that allow you to catch and handle exceptions or errors in Python.

  • try: Block of code that is attempted.
  • except: Block of code that runs if an error occurs in the try block.

This prevents the program from crashing due to an unexpected error.


Basic Syntax

try:
    # Code that may cause an error
    result = 10 / 0
except ZeroDivisionError:
    # Code that runs if an error occurs
    print("Cannot divide by zero")

Explanation:

  1. Python tries to execute the try block.
  2. If a ZeroDivisionError occurs, Python executes the except block.
  3. If no error occurs, the except block is ignored.

Catching Multiple Exceptions

You can handle different types of errors using multiple except blocks:

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

Catching All Exceptions

You can also catch any type of exception:

try:
    file = open("nonexistent_file.txt")
except Exception as e:
    print(f"An error occurred: {e}")

⚠️ Note: Using except Exception catches all errors, but it is not recommended to use it always, as it may hide important issues.


Else and Finally Blocks

Python allows using else and finally along with try and except:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("You must enter a valid number")
else:
    print(f"The result is {result}")
finally:
    print("This block always runs, whether an error occurs or not")
  • else: Runs if no error occurs.
  • finally: Runs always, useful for releasing resources like files or connections.

Best Practices When Using Try Except

  1. Catch specific errors, avoid using a generic except unless necessary.
  2. Do not use try to control program logic; use it only for handling errors.
  3. Use finally to release critical resources (files, database connections).
  4. Add clear messages to help debug errors.

Complete Example: File Handling

try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist")
except PermissionError:
    print("You do not have permission to read the file")
else:
    print(content)
finally:
    print("Process completed")

DJC > Tutorials