What is the difference between try-except and try-finally?

The primary difference between try-except and try-finally lies in their purpose and behavior:


try-except: Handling Exceptions

  • Purpose: Used to catch and handle exceptions that occur in the try block.
  • Behavior:
    • If an exception occurs in the try block, the corresponding except block is executed to handle it.
    • If no exception occurs, the except block is skipped.
  • Use Case: When you want to manage specific errors and ensure the program continues running.

Example:

try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")

try-finally: Ensuring Cleanup

  • Purpose: Ensures that the finally block is executed regardless of whether an exception occurs or not.
  • Behavior:
    • The finally block always executes, even if the try block raises an exception or the program exits via return, break, or continue.
    • If an exception is not handled within the try block, the program may still terminate after the finally block is executed.
  • Use Case: When you need to release resources (e.g., close files, release locks) or perform cleanup actions.

Example:

try:
    f = open("example.txt", "r")
    data = f.read()
finally:
    f.close()  # Ensures the file is closed whether or not an exception occurs

Combining try-except with finally

You can use both try-except and finally together to handle exceptions and ensure cleanup.

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Handled exception: Cannot divide by zero!")
finally:
    print("This will always execute, for cleanup purposes.")

Key Differences in Summary:

Featuretry-excepttry-finally
Primary PurposeHandle exceptions gracefully.Ensure cleanup or final actions.
When Block Executesexcept runs only when an exception occurs.finally always runs, exception or not.
Exception HandlingCatches and processes exceptions.Does not handle exceptions.
Resource ManagementNot specifically for cleanup.Ensures resources are cleaned up.

In essence: Use try-except to handle specific errors, and try-finally to guarantee resource cleanup or final actions, even when exceptions occur.