Why use else in try / except construct in Python?

I am learning Python and stumbled upon a concept that I cannot easily learn: an optional else block inside a try construct.

According to the documentation :

The try ... except statement has an optional else clause, which, when present, should follow everything except the caveats. This is useful for code that should be executed if the try clause does not raise an exception.

What am I confused about why the code should be executed if the try clause does not throw an exception inside the try construct - why not just execute it after try / except at the same level of indentation? I think this will simplify exception handling options. Or another way to ask if this is code that is in the else block, it won’t do it if it just executed the try statement, regardless of it. Maybe I'm missing something, enlighten me.

This question is somewhat similar to this , but I could not find there what I was looking for.

+8
python exception-handling try-catch
source share
2 answers

The else block is executed only if the code in try does not raise an exception; if you put the code outside the else block, this will happen regardless of exceptions. In addition, this happens before finally , which is usually important.

This is usually useful when you have a small piece of customization or verification, which may be an error, followed by a block in which you use the resources you created in which you do not want to hide the errors. You cannot put code in try , because errors can go to except clauses when you want them to be propagated. You cannot expose it outside the construct because the resources are definitely unavailable there, because the installation failed or because finally lost everything. So you have an else block.

+11
source share

One use case might be to prevent users from defining a flag variable to check if an exception has been raised (as in a for-else loop).

A simple example:

 lis = range(100) ind = 50 try: lis[ind] except: pass else: #Run this statement only if the exception was not raised print "The index was okay:",ind ind = 101 try: lis[ind] except: pass print "The index was okay:",ind # this gets executes regardless of the exception # This one is similar to the first example, but a `flag` variable # is required to check whether the exception was raised or not. ind = 10 try: print lis[ind] flag = True except: pass if flag: print "The index was okay:",ind 

Output:

 The index was okay: 50 The index was okay: 101 The index was okay: 10 
+4
source share

All Articles