Lab 4 of 5
Β·
Semi-Guided
Use finally to Always Log Completion
Objective: Use try/except/finally so the script always prints a summary even when an error occurs.
Instructions
Create a file called lab4.py. The script below processes a device list but hits an error midway. Add a finally block so the script always prints how many devices were processed and a completion message β even when it fails.
devices = ["sw-core-01", "sw-access-01", "missing-device"]
results = []
try:
for device in devices:
if device == "missing-device":
raise ConnectionError(f"Cannot reach {device}")
results.append(f"{device}: processed")
except ConnectionError as e:
print(f"Error: {e}")
finally:
# Add your finally block here
pass
Your output must match exactly:
Error: Cannot reach missing-device
Processed 2 of 3 devices
Script complete
Run it with python3 lab4.py. Paste your output below and submit.
Starter Code
devices = ["sw-core-01", "sw-access-01", "missing-device"]
results = []
try:
for device in devices:
if device == "missing-device":
raise ConnectionError(f"Cannot reach {device}")
results.append(f"{device}: processed")
except ConnectionError as e:
print(f"Error: {e}")
finally:
pass
π‘ Show Hint
Replace "pass" in the finally block with two print statements: one using len(results) and len(devices), one saying "Script complete".
Paste Your Output