else and finally

Cleanup and success blocks

Interview Relevant: Complete exception handling

Else and Finally

else: runs if no exception. finally: runs always.

Code Examples

python
1try:
2    f = open("file.txt")
3except FileNotFoundError:
4    print("Missing file")
5else:
6    print("File opened successfully")
7finally:
8    print("Cleanup operations")

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In