What Are Python Exception Handling Techniques? See Examples

In Python, exceptions are errors that occur during program execution. Exception handling allows you to catch and manage errors gracefully without crashing the program.

Python provides the following constructs:

  • try: Wrap code that may raise an exception
  • except: Handle specific or general exceptions
  • else: Execute code if no exception occurs
  • finally: Execute cleanup code regardless of exception
  • raise: Manually trigger an exception

Why Exception Handling Is Important

  • Prevents program crashes
  • Enables graceful recovery from errors
  • Helps in debugging and logging errors
  • Essential for real-world applications like file handling, APIs, and user input

Example:

try:
    x = int(input("Enter a number: "))
    print(10 / x)
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("Execution complete.")

Example 1: Handling File Operations

try:
    with open("data.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found. Please check the filename.")
finally:
    print("File operation attempted.")
  • Ensures the program continues even if the file is missing

Example 2: Real-World Scenario – API Request

import requests

try:
    response = requests.get("https://api.github.com")
    response.raise_for_status()  # Raise exception for HTTP errors
    data = response.json()
    print("API data fetched successfully")
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"Error occurred: {err}")
  • Handles network errors, HTTP errors, and unexpected issues

Example 3: Using else and finally

try:
    num = int(input("Enter a number: "))
except ValueError:
    print("Invalid number!")
else:
    print(f"You entered: {num}")
finally:
    print("Program finished.")
  • else executes only if no exception occurs
  • finally always executes

Example 4: Raising Custom Exceptions

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or older")
    return True

try:
    check_age(16)
except ValueError as e:
    print(f"Error: {e}")
  • Allows developers to define custom error rules for their programs

Best Practices

✔ Always handle specific exceptions rather than using a general except:
✔ Use finally to clean up resources like files or network connections
✔ Raise custom exceptions for meaningful error messages
✔ Log exceptions for debugging and monitoring


Conclusion

Python exception handling techniques allow developers to write robust, error-proof programs. Using try, except, finally, and raise ensures programs continue running smoothly, making your code reliable in real-world applications.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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