PYTHON

Python try except: Handling Exceptions in Python

The try...except block in Python handles specific exceptions (errors) without causing programs to crash.

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 tasks.

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, the try...except block is ideal whenever you expect certain types of errors and want to handle them.

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}")

File Operations

File operations often need error handling for issues like file or directory not found. This prevents the program from crashing when a file operation fails.

try:
    with open("file.txt", "r") as file:
        content = file.read()
except FileNotFoundError as e:
    print(f"File not found: {e}")

Network Operations

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.

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}")

Iterating Over Data

When processing lists or other iterables, you can handle exceptions that occur within the loop. For example, a game might process a list of player scores and handle invalid entries:

data = [1, 2, "three", 4]

for item in data:
    try:
        result = 10 / item
    except TypeError as e:
        print(f"Invalid item type: {e}")
    except ZeroDivisionError as e:
        print(f"Division by zero: {e}")

APIs and Web Scraping

Applications working with APIs or web scraping might manage potential errors because of missing data or incorrect URLs. For example, an application might fetch user data from a social media API:

try:
    data = some_api.get_data("endpoint")
except some_api.APIError as e:
    print(f"API error: {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 tasks.

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

Combining try, except, else, and finally Clauses

You can combine all four blocks for comprehensive error handling and cleanup. This provides a structured way to handle errors and ensure necessary cleanup happens.

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

Multiple Python except Clauses

You can handle different exceptions in separate except blocks. This allows you to provide specific error messages or actions for different types of errors.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Cannot divide by zero: {e}")
except TypeError as e:
    print(f"Invalid type: {e}")

Using try...except with Loops

When working with loops, place try...except inside the loop to continue processing even if an error occurs. This is useful for processing data where some elements may cause exceptions.

data = ["10", "20", "a", "30"]

for item in data:
    try:
        print(int(item) * 2)
    except ValueError as e:
        print(f"Error converting '{item}': {e}")

Nested try...except Blocks

You can nest try...except blocks for more granular error handling. This allows you to handle errors at different levels of your code.

try:
    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        print(f"Inner error: {e}")
except Exception as e:
    print(f"Outer error: {e}")

Exceptions vs. Syntax Errors

try...except blocks can catch exceptions but don’t work with syntax errors.

Exceptions are errors that occur during the execution of a program, while syntax errors are mistakes in the code that prevent the program from running at all. Syntax errors occur when the Python parser detects code that does not conform to the syntax rules of the language.

For example, a syntax error occurs when you forget a colon at the end of an if statement:

if True
    print("This will cause a syntax error")

In contrast, an exception occurs when the code is syntactically correct but something goes wrong during execution, such as trying to divide by zero:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Cannot divide by zero: {e}")

Raising Errors

Using the raise statement, you can raise exceptions to later catch with try...except. This is useful when you want to signal that an error occurred, even if the code itself doesn’t naturally raise an exception. Raising errors can help enforce certain conditions or validation checks.

def check_positive(number):
    if number <= 0:
        raise ValueError("Number must be positive")
    return number

try:
    check_positive(-10)
except ValueError as e:
    print(f"Error: {e}")
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.

© 2024 Mimo GmbH