Skip to content

1.4 Error Handling

Reid Russom edited this page Oct 2, 2024 · 1 revision

Error Handling

Error handling in Python is managed using the try, except, else, and finally blocks. This structure allows developers to gracefully handle errors that may occur during runtime, ensuring that the program can either recover from an issue or fail gracefully with useful feedback.

try and except

The try block contains code that might raise an error. If an error occurs, the except block is executed, and Python will not terminate the program abruptly. You can catch specific exceptions or handle all exceptions generally.

Example: Handling a specific exception

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

Example: Handling any exception

try:
    num = int(input("Enter a number: "))
except Exception as e:
    print(f"An error occurred: {e}")

else

The else block is optional and runs if no exception was raised in the try block.

Example: Using else for successful execution

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
else:
    print(f"Success! The result is {result}.")

finally

The finally block runs regardless of whether an exception occurred or not. It’s often used for cleanup actions like closing files or database connections.

Example: Using finally for cleanup

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found.")
finally:
    file.close()
    print("File closed.")

Raising exceptions

Python allows you to raise exceptions using the raise keyword, either with built-in exceptions or custom ones.

Raising a custom exception

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(e)

Summary

Error handling in Python enables more robust and maintainable code by catching potential issues, allowing graceful recovery, and ensuring proper resource management. You'll use try, except, else, and finally in this week's assignment by... TBD