What is even better for Python?

I am trying to learn the small details of Python, and I came up with a try-else statement .

try1_stmt ::= "try" ":" suite ("except" [expression [("as" | ",") target]] ":" suite)+ ["else" ":" suite] ["finally" ":" suite] 

The optional else clause is executed if and when control flows from the end of the try clause. Exceptions in the else clause are not handled by previous exceptions.

I cannot think of a case where this would be useful. Usually there is no practical difference between putting code at the end of a try block or an else block.

What is an else clause? Is it used in some kind of real code?

+7
source share
2 answers

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.

+7
source

The presence of "excess" material at the end of the try block, at least in my opinion, is a bit of a smell of code. The try block should contain only lines (lines) that, in your opinion, are at risk of throwing an exception, preferably only one line.

This avoids any case of accidentally detecting an exception from a string that you did not suspect can throw (and possibly handle it incorrectly). The else block allows you to code this in a cleaner way.

+4
source

All Articles