Friday, 4 December 2026

Python Try-Else

Discussing some stuff with a GPT it came up with a code sample using one of those odd Python features I had never used nor even tried to understand, try-else. The idea is that the code in the else block only executes if the code in the try block executes to its end (does not throw an exception or exits via break/return). Let's see an example:



try:
    x = int(s)
except ValueError:
    print("bad input")
else:
    do_something_that_might_raise_value_error(x)
do_something_else()


The use case for this construct is that we have 2 statements that can throw the same type of exception, but we only want to catch the exception in the first statement, and we only want to execute the second statement if the first statement succeeded. The above construct is equivalent to this more verbose one:



failed = False
try:
    x = int(s)
except ValueError:
    print("bad input")
    failed = True

if not failed:
    do_something_that_might_raise_value_error(x)
do_something_else()


Python and Ruby seem to be the only 2 mainstream languages featuring this kind of construct (begin-rescue-else-finally in Ruby.

Python          Ruby
------          ----
try             begin
except          rescue
else            else
finally         ensure

An alternative to try-else and to the verbose syntax using the extra "failed" variable is structuring the code so that the catch block does a return, but this does not always fit the code flow.



try:
    x = int(s)
except ValueError:
    print("bad input")
    return
else:
    do_something_that_might_raise_value_error(x)

# this function has to be moved outside, to the caller:
# do_something_else()