Skip to main content

6.1 Errors and Exceptions

Python distinguishes syntax errors from runtime exceptions.

Syntax errors vs exceptions

  • Syntax errors: detected while parsing code.
  • Exceptions: raised during execution (e.g., TypeError, ValueError, OSError).

Handling with try/except

try:
value = int(input("Enter number: "))
except ValueError:
print("Invalid integer")

else and finally

  • else runs only if no exception occurred in try.
  • finally runs regardless of success/failure, useful for cleanup.
try:
f = open("data.txt")
except OSError:
print("Could not open file")
else:
print(f.readline())
f.close()

Raising and chaining

try:
connect_db()
except ConnectionError as exc:
raise RuntimeError("Database startup failed") from exc

Context managers (with)

Prefer with to guarantee cleanup for resources like files and sockets.

with open("data.txt") as f:
data = f.read()

Official references