else and finally
In this tutorial, we'll run code after success or cleanup code no matter what.
try / except can also use else and finally.
else runs only if no exception happened.
try:
number = int("42")
except ValueError:
print("Invalid number")
else:
print("Conversion worked:", number)
Why Use else?
You could put everything in the try block, but else keeps successful follow-up code separate from risky code.
try:
age = int(input("Age: "))
except ValueError:
print("Invalid age")
else:
print("Next year:", age + 1)
Only the conversion is risky. The success message belongs in else.
finally
finally runs no matter what:
try:
number = int("hello")
except ValueError:
print("Invalid number")
finally:
print("Finished attempt")
Output:
Invalid number
Finished attempt
finally is often used for cleanup, such as closing files or network connections.
The Full Shape
try:
risky_code
except SomeError:
handle_error
else:
run_if_successful
finally:
always_run_this
You do not need all four parts every time. Most beginner code uses just try and except.
A Practical Example
try:
number = int(input("Number: "))
except ValueError:
print("That was not a number")
else:
print("Squared:", number * number)
finally:
print("Thanks for trying")
This separates the risky conversion, the error message, the successful calculation, and the final message.
Practice
Ask for a number. Use else to print the doubled value if conversion succeeds. Use finally to print "Done".