Python try-except-else-finally Explained with Examples

Similar to try-except-finally, try-except-else-finally adds a opitonal else block.

Syntax

try:
    # Code that may raise an exception
    # ...
except ExceptionType as e:
    # Code to handle the exception
    # ...
else:
    # Code that executes if no exception is raised
    # ...
finally:
    # Cleanup code that will always execute
    # ...

Else Block

The else block is optional and is executed if no exceptions were raised in the try block. It is useful when you want to execute code only if the try block completes successfully.

Examples

Try-Except-Else

try:
    x = int(input("Enter a number: "))
except ValueError:
    print("Invalid input. Please enter a number.")
else:
    print("You entered a valid number:", x)

In this example, if the input is a valid number, the else block is executed. If the input is not a number, a ValueError is raised and caught, and the else block is skipped.

Try-Except-Else-Finally

try:
    x = int(input("Enter a number: "))
except ValueError:
    print("Invalid input. Please enter a number.")
else:
    print("You entered a valid number:", x)
finally:
    print("This will always be printed.")

Here, the code attempts to convert user input to an integer. If the input is a valid number, the else block is executed. If the input is not a number, a ValueError is raised and caught. Regardless of whether an exception occurs, the finally block is executed.