Some magic spells leave a mess. Maybe you opened a portal, but forgot to close it.
Even if the spell fails (errors), we must clean up. We need a way to say: "Do this no matter what happens."
The finally Spell
The finally block creates a guarantee. It runs after the try and except blocks, always.
try:
print("Opening box...")
# Maybe error here
except:
print("Something broke!")
finally:
print("Closing box.") # This ALWAYS runs
1
The Unclosed Portal
The portal opens, but if teleport_hoppy crashes, it stays open! Dangerous.
2
Add the Cleanup
Add a finally: block inside the function.
3
Close it
Inside finally, print "Closing portal..." and set portal_status = "Closed". Then watch it run even after the crash!
finally is perfect for "cleaning up" — like saving a file, closing a connection, or resetting a switch, even if your main code explodes.
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
def teleport_hoppy():
global portal_status
try:
print("Opening portal...")
print(1 / 0) # Crash!
print("Teleporting...")
except:
print("Teleport failed!")
finally:
print("Closing portal...")
portal_status = "Closed"Advanced TipsWant more? Click to expandClick to collapse
F. The Unstoppable Block
- The code inside
finallyruns even if youreturninside thetryblock! - It's the most reliable place to clean up resources (like closing files or database connections).
Loading...
Terminal
Terminal
Ready to run...