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
elseruns only if no exception occurred intry.finallyruns 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
- Tutorial errors/exceptions: https://docs.python.org/3/tutorial/errors.html
trystatement reference: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement- Built-in exceptions: https://docs.python.org/3/library/exceptions.html