Understanding try-except-else-finally in Python


Use else for code that should run if the try block does not raise an error, and finally for code that should always run.

Source Code

try:
    print("Trying...")
    # risky operation
except Exception as e:
    print("Exception occurred:", e)
else:
    print("Success, no exceptions!")
finally:
    print("Always executes, cleanup goes here.")
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments