Python handles runtime errors using a
try/except/else/finallyblock structure to prevent programs from crashing unexpectedly.The
elseblock runs only if no exceptions occur in thetryblock, while thefinallyblock always executes regardless of what happened.try block:You place code that might raise an error inside this block. If an error occurs, Python stops running the remaining lines intryand jumps straight to a matchingexceptclause.except block:This catches and handles specific exceptions so your program can recover gracefully. You can stack multipleexceptblocks to handle different error types separately.else block:This runs exclusively when thetryblock finishes without raising any exceptions.finally block:This executes every single time, whether an exception occurred, was caught, or even if areturnstatement was triggered earlier. Developers use it for guaranteed cleanup tasks like closing files or network connections.
def read_number_from_file(filename):
file = None
try:
file = open(filename, "r")
data = file.read().strip()
number = int(data)
except FileNotFoundError:
print("Error: The file does not exist.")
except ValueError:
print("Error: The file does not contain a valid integer.")
else:
# Runs ONLY if open(), read() and int() all succeeded
print(f"Success! Doubled number: {number * 2}")
finally:
# Runs ALWAYS, even if an error happened above
if file:
file.close()
print("Cleanup: File closed.")
read_number_from_file("data.txt")