Robust Error Handling in Python

Python Logo

Proper error handling makes your code more robust and predictable. Python uses the `try...except` block to handle exceptions, which are errors detected during execution.

The `try...except` Block

The `try` block contains code that might raise an exception. If an error occurs, the code in the `except` block is executed.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: Cannot divide by zero. ({e})")

Handling Multiple Exceptions

You can handle different types of exceptions with multiple `except` blocks.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

The `else` and `finally` Clauses

  • `else`: The code in the `else` block runs only if no exceptions were raised in the `try` block.
  • `finally`: The code in the `finally` block runs no matter what, whether an exception occurred or not. It's often used for cleanup operations, like closing a file.
try:
    file = open('data.txt', 'r')
    content = file.read()
except FileNotFoundError:
    print('File not found!')
else:
    print('File content:', content)
finally:
    if 'file' in locals() and not file.closed:
        file.close()
        print('File closed.')

Comments