Handling Multiple Exceptions in Python Examples

Explore practical examples of handling multiple exceptions in Python for robust error management.
By Jamie

Exception handling is a crucial aspect of programming that allows developers to manage errors gracefully. In Python, you can handle multiple exceptions to ensure that your code remains robust and user-friendly. Below are three diverse examples that illustrate how to handle multiple exceptions effectively.

Example 1: File Operations with Multiple Exceptions

Context

When dealing with file operations, several exceptions can arise, such as file not found or permission errors. This example demonstrates how to handle these scenarios.

try:
    with open('data.txt', 'r') as file:
        data = file.read()
except FileNotFoundError:
    print("Error: The file was not found.")
except PermissionError:
    print("Error: You do not have permission to access this file.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

In this example, we attempt to open and read a file called ‘data.txt’. If the file is missing, a FileNotFoundError is raised, which is handled by printing a user-friendly message. Similarly, if there are permission issues, a PermissionError is caught. The catch-all Exception handler addresses any other unforeseen errors, ensuring that the program does not crash unexpectedly.

Example 2: User Input Validation

Context

When accepting user input, it’s essential to validate that input correctly. This example shows how to handle multiple exceptions that can occur during input conversion.

user_input = input("Enter a number: ")
try:
    number = int(user_input)
    print(f"You entered: {number}")
except ValueError:
    print("Error: Please enter a valid integer.")
except TypeError:
    print("Error: An unexpected type was input.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

In this scenario, the program prompts the user to enter a number. The input is then attempted to be converted into an integer. If the user inputs a non-integer value, a ValueError is raised, which is handled appropriately. The TypeError could occur if there’s an unexpected type in the input, though it’s less common here. The catch-all Exception ensures any other errors are also managed gracefully.

Example 3: Network Requests

Context

When making network requests, various exceptions can occur, such as connectivity issues or timeouts. This example demonstrates handling multiple exceptions in a network request scenario using the requests library.

import requests

url = 'https://api.example.com/data'
try:
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    print(data)
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError:
    print("Error: Network connection failed.")
except requests.exceptions.Timeout:
    print("Error: The request timed out.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

In this example, we are trying to fetch data from a specified URL. If there’s an HTTP error, such as a 404 or 500 status code, the HTTPError exception is raised. A ConnectionError handles issues with network connectivity, while a Timeout exception is caught if the request takes too long. The general Exception handler ensures that any unforeseen issues are also addressed.

By implementing these examples of handling multiple exceptions in Python, developers can create more resilient applications that provide informative feedback to users, enhancing the overall user experience.