Python Docs

Python Try–Except — Else & Finally Cheat Sheet

Using the "else" Block

The else block executes only if the try block does not raise any error. It is useful for running code that should execute only when everything goes correctly.

Example

Since no error occurs, the else block executes:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Using the "finally" Block

The finally block will run no matter what happens — whether an error occurs or not. This makes it ideal for closing resources such as files, databases, or network connections.

Example

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The try-except is finished")

Using finally for File Handling

This example shows how try–except–finally ensures a file is always closed, even if something goes wrong while writing.

try:
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")

This prevents memory leaks and keeps file operations safe.

Summary

  • else — Runs only when no errors occur.
  • finally — Runs always, even if errors occur.
  • Use finally for cleanup (closing files, freeing memory).
  • Combining try + except + else + finally gives full control over error handling.