Python: Handle Exceptions with Try and Except

Python Exception Handling Tutorial

Python Exception Handling Tutorial

This tutorial will guide you through handling exceptions in Python using the `try` and `except` blocks. Understanding how to gracefully handle errors is crucial for writing robust and reliable Python programs.

Understanding Exceptions

An exception is an event that disrupts the normal flow of a program’s execution. When an exception occurs, Python looks for an `except` block that can handle that specific type of exception. If no matching `except` block is found, the program will terminate, and an error message will be printed. The `try` block contains the code that might raise an exception, and the `except` block contains the code to handle it.

Example 1: Basic Try and Except

This example demonstrates the simplest form of `try` and `except`, handling a `ZeroDivisionError`.


try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
    result = 0  # Assign a default value to avoid a completely broken program
finally:
    print("This always executes, regardless of errors.")

In this example:

  • The code within the `try` block attempts to divide 10 by 0, which is an invalid operation and raises a `ZeroDivisionError`.
  • The `except ZeroDivisionError` block catches this specific error.
  • The code within the `except` block prints an error message and assigns a default value of 0 to `result`. This prevents the program from crashing.
  • The `finally` block is always executed, regardless of whether an exception occurred or not. It’s commonly used for cleanup tasks (e.g., closing files).

Common Mistake: Not assigning a value to `result` within the `except` block. If you don’t, `result` will be undefined, potentially leading to further errors later in the program. It’s good practice to always provide a default value or handle the error in a meaningful way.


try:
    result = 10 / 0
except ZeroDivisionError:
    # Missing: result = 0  # This would cause an error if used later
    print("Error: Division by zero")
finally:
    print("This always executes")

Output:


Error: Division by zero
This always executes

Example 2: Handling Different Exception Types

This example demonstrates handling multiple exception types in a single `try` block.


try:
    num = int("abc")  # This will raise a ValueError
    result = 10 / num
except ValueError:
    print("Error: Invalid input.  Please enter a number.")
except ZeroDivisionError:
    print("Error: Division by zero")
finally:
    print("This always executes")

Here, we have two potential exceptions: `ValueError` (if the input string cannot be converted to an integer) and `ZeroDivisionError` (if the resulting division is by zero). The code first tries to convert the string “abc” to an integer. If that fails, the `ValueError` block is executed. If a `ZeroDivisionError` occurs after the conversion to integer (which doesn’t happen in this example), the `ZeroDivisionError` block would be executed.


try:
    num = int("abc")
    result = 10 / num
except ValueError:
    print("Error: Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Error: Division by zero")
finally:
    print("This always executes")

Output:


Error: Invalid input. Please enter a number.
This always executes

Example 3: Mathematical Calculations with Exception Handling

This example demonstrates handling potential errors when performing mathematical calculations with floating-point numbers.


def calculate_average(numbers):
    total = 0
    for num in numbers:
        total += float(num)  # Convert to float to handle decimals
    if len(numbers) == 0:
        raise ValueError("Cannot calculate the average of an empty list.")
    average = total / len(numbers)
    return average

try:
    data = ["10", "20", "30"]
    avg = calculate_average(data)
    print("Average:", avg)

    data2 = []
    avg2 = calculate_average(data2) #Will raise ValueError
    print("Average:", avg2)
except ValueError as e:
    print("Error:", e)

Explanation:

  • The `calculate_average` function takes a list of numbers (as strings) and calculates their average.
  • It converts each number to a float using `float(num)` to handle decimal values.
  • It checks if the list is empty and raises a `ValueError` if it is, since division by zero would occur.
  • The `try` block calls the `calculate_average` function with the `data` list.
  • If the function succeeds, the average is printed.
  • If a `ValueError` is raised (e.g., due to an empty list), the `except ValueError` block catches it and prints the error message.

try:
    data = ["10", "20", "30"]
    avg = calculate_average(data)
    print("Average:", avg)

    data2 = []
    avg2 = calculate_average(data2) #Will raise ValueError
    print("Average:", avg2)
except ValueError as e:
    print("Error:", e)

Output:


Average: 20.0
Error: Cannot calculate the average of an empty list.

Key Takeaways

Remember:

  • `try` blocks enclose code that might raise exceptions.
  • `except` blocks handle specific exception types.
  • The `finally` block always executes, regardless of exceptions.
  • It’s essential to provide default values or handle errors gracefully to prevent your program from crashing.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.