Advanced try Block Components
The else Clause
The else block runs only if the code inside the try block executes successfully (i.e., no exception was raised).
Use Case: Perform operations that depend on the successful execution of the try block, but which might fail themselves (keeping the try block clean).
python while True: try: user_input = int(input("Enter a number: ")) except ValueError: print("Invalid input. That was not a whole number.") else: # Runs ONLY if the int(input(...)) conversion was successful print(f"Successfully read number: {user_input}") break
The finally Clause
The finally block executes regardless of whether an exception occurred or not, and regardless of whether the try block completed or was terminated early (e.g., by a return or break).
Use Case: Cleanup operations, like closing file connections or releasing network resources.
python resource = None try: # Assume we open a connection here resource = 1 result = 10 / 0 # This will raise ZeroDivisionError except ZeroDivisionError: print("Caught the division error.") finally: # This always runs if resource: print("Cleanup: Closing resource.") # Program exits gracefully after cleanup