PYTHON

Python try except: Handling Exceptions in Python

The try...except block in Python handles specific exceptions (errors) without causing programs to crash. Exception handling is essential for beginners and experienced developers alike, ensuring that Python programs run smoothly even when errors occur.

How to Use try...except in Python

The try...except statement consists of a try block, one or more except blocks, and optional else and finally blocks. Here’s the basic syntax:

try:
    # Code that might raise an exception
except SomeException as e:
    # Code that runs if the exception occurs
else:
    # Code that runs if no exception occurs (optional)
finally:
    # Code that always runs, regardless of exceptions (optional)
  • try: The block of code where errors might occur.
  • except SomeException as e: The block of code to handle specific exceptions.
  • else: (Optional) The block of code that runs if the try block doesn’t raise an exception.
  • finally: (Optional) The block of code that runs no matter what, often used for cleanup actions such as closing files.

Basic Usage

try:
    # Code that might raise an exception
except:
    # Code that runs if any exception occurs

When to Use try...except in Python

In Python code, the try...except block is ideal whenever you expect certain types of errors and want to handle them efficiently.

Handling User Input Errors

When processing input from users, you can use try...except to manage invalid input. This ensures the program does not crash because of unexpected input types.

try:
    user_age = int(input("Enter your age: "))
except ValueError as e:
    print(f"Invalid input: {e}")

Additionally, if you are reading user-provided filename inputs, exception handling prevents errors when files are missing.

try:
    filename = input("Enter filename: ")
    with open(filename, "r") as file:
        content = file.read()
except FileNotFoundError:
    print(f"Error: The file {filename} was not found.")

File Operations and Windows Compatibility

File operations often need error handling for issues like missing filename or incorrect permissions. This is especially important when working with Windows file systems, where paths and permissions may vary.

try:
    with open("C:\\Users\\file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found in Windows system.")

Network Operations and API Calls

Handling network operations ensures that your program behaves correctly when there are connectivity issues. This is important for applications that rely on external network resources and API calls.

import requests

try:
    response = requests.get("http://example.com")
except requests.ConnectionError as e:
    print(f"Network error: {e}")

Examples of Using try in Python

Database Connections

Applications connecting to databases can use try...except to handle connection errors. For instance, a financial application might connect to a database to retrieve stock prices:

try:
    connection = some_database.connect()
except some_database.ConnectionError as e:
    print(f"Failed to connect to database: {e}")

Handling Built-in Exceptions in Python

Python has many built-in exceptions, such as ZeroDivisionError, TypeError, and IndexError. These exceptions help programmers quickly identify common issues.

try:
    result = 10 / 0  # This raises a ZeroDivisionError
except ZeroDivisionError as e:
    print(f"Error: {e}")

Creating Custom Exceptions in Python

In addition to built-in exceptions, developers can create custom exceptions to handle application-specific errors.

class CustomError(Exception):
    """Custom exception for specific error handling"""
    pass

try:
    raise CustomError("Something went wrong")
except CustomError as e:
    print(f"Custom exception occurred: {e}")

Learn More About Python try except

Python try...except...else

The else block allows you to execute code only when no exceptions occur. This is useful for running code that should only execute if the try block is successful.

try:
    result = 10 / 2
except ZeroDivisionError as e:
    print(f"Error: {e}")
else:
    print("No errors occurred, result is", result)

Python try...except...finally

The finally block executes code that must run no matter what, such as closing files or releasing resources. This is often used for cleanup actions.

try:
    file = open("file.txt", "r")
    content = file.read()
except IOError as e:
    print(f"File error: {e}")
finally:
    file.close()

Handling Multiple Python Exceptions

Python allows handling multiple exceptions in a single try-except block. This is particularly useful in debugging complex Python programs.

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

Using try-except for Debugging and Tracebacks

The try-except block is useful for debug operations. By catching errors, programmers can analyze traceback details and locate the source of errors.

import traceback

try:
    raise ValueError("An error occurred")
except ValueError as e:
    print("Error detected:")
    traceback.print_exc()

Using try-except in Java

Although this guide focuses on Python exception handling, other languages, like Java, also use similar structures for handling errors.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: Division by zero");
}

Understanding Python Exception Class Hierarchy

All exceptions in Python are derived from the base exception class, BaseException. This hierarchy allows for structured and modular error handling.

try:
    raise ValueError("Custom message")
except Exception as e:  # Catching a general Exception class
    print(f"Exception caught: {e}")

Using try-except with the Doctype and Backend Systems

Exception handling is crucial in backend development where errors may occur when processing HTTP requests, handling databases, or parsing documents such as doctype declarations.

try:
    from bs4 import BeautifulSoup
    html = "<!DOCTYPE html><html><head><title>Example</title></head></html>"
    soup = BeautifulSoup(html, "html.parser")
    print(soup.doctype)
except ImportError:
    print("BeautifulSoup module is missing.")

The try-except structure is a powerful tool for managing errors in Python code. Whether handling built-in exceptions, writing custom exceptions, or ensuring cleanup actions with finally, mastering exception handling is essential for every programmer.

If you're new to error handling, consider following our Python tutorial course to get hands-on experience with exception handling in real-world scenarios.

Learn Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH