How Python Handles Exceptions

The Role of the Interpreter

When Python encounters an error, the interpreter stops executing the current block of code and looks for an appropriate handler to address the exception. If no handler is found, the program terminates.

Default Exception Handling

If an exception isn’t caught, Python provides a default handler that:

  • Prints a traceback, showing where the error occurred.
  • Displays the type of exception and an error message.
  • Terminates the program.

Using Try and Except Blocks

Python allows you to handle exceptions using try and except blocks. This structure lets you execute a block of code and catch exceptions that may arise, providing specific responses for different errors.

Example:

try:
    # Code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Else and Finally Clauses

  • else Clause: Executes if no exceptions are raised in the try block.
  • finally Clause: Executes regardless of whether an exception occurred, often used for cleanup tasks.

Example:

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