Usually there is no practical difference between putting code at the end of a try block or in an else block.
What is the else clause for?
The most interesting is the else clause. It starts when there is no exception, but before the final sentence. This is his one use case for which there is no reasonable alternative.
Without the else clause, the only option to run additional code before finalizing will be the clumsy practice of adding code to try-clause. This is inconvenient because it risks excluding exceptions from code that was not intended to be protected with a try block.
The case of using additional unsecured code before finalization does not occur very often. Therefore, do not expect to see many examples in the published code. This is somewhat rare.
Another option is to use else-clause so that it performs actions that should occur when an exception does not occur and which do not occur when handling exceptions. For example:
recip = float('Inf') try: recip = 1 / f(x) except ZeroDivisionError: logging.info('Infinite result') else: logging.info('Finite result')
Finally, the most common use of an else clause in a try block is a little fragrance (aligning exceptional results and exclusive results at the same level of indentation). This use is always optional and not strictly necessary.
Is it used in some kind of real code?
Yes, there are a few examples in the standard library.
Raymond hettinger
source share