The before code crashes if the file does not exist because it does not handle exceptions. The after code uses a try-except block to catch the FileNotFoundError, prints a friendly message, and returns None to allow the program to continue safely.
### Before: No emergency handling
def read_file(filename):
with open(filename, 'r') as f:
data = f.read()
return data
print(read_file('missing.txt')) # This will crash if file not found
### After: With emergency handling
def read_file(filename):
try:
with open(filename, 'r') as f:
data = f.read()
return data
except FileNotFoundError as e:
print(f"Error: File {filename} not found.")
return None
print(read_file('missing.txt')) # Prints error message and returns None