1. The Core Syntax: try, except, else, and finally
The complete exception block consists of four clauses, though you'll rarely use all four at once.
try:
# 1. Code that might raise an exception
file = open("data.txt", "r")
content = file.read()
value = int(content.strip())
except FileNotFoundError:
# 2. Runs ONLY if a FileNotFoundError occurs
print("Error: The file does not exist.")
except ValueError:
# 3. Runs ONLY if the content couldn't be turned into an int
print("Error: The file content is not a valid integer.")
else:
# 4. Runs ONLY if the try block succeeded with ZERO exceptions
print(f"Success! The value is {value}")
finally:
# 5. ALWAYS runs, no matter what (even if the code crashed or returned)
print("Cleaning up resources...")
try:
file.close()
except NameError:
pass # File was never opened
Placing code in the else block rather than the try block keeps your try block small. This ensures you don't accidentally catch an exception from code you weren't trying to protect.