First, the concept
Abnormal:
Common Exception Statements:
1. Try except Else2. Try Finally3. Raise4. Assert5. With AS
Second, the role of else
First, look at the exception and else in action:
Except: Capturing exception items in a try, such as indexexception, SyntaxError, or the exception handler;
ELSE: The statement in the else is executed only if there is no exception in the try;
Here, I came up with two questions: 1. What is the time of the else use? 2. What is the difference between being and not being else?
Example 1:
def fetcher (obj, index): return obj[index]x = ' spam ' Try:print fetcher (x, 3) except Exception:print ' HHH ' else:print ' has no E Xception ' Print fetcher (x, 2) print '---' * 10try:print fetcher (x, 4) except Indexerror:print ' got exception ' Else:print ' has No exception ' Print Fetcher (x, 2)
Operation Result:
MHAs no Exceptiona------------------------------got exception
As you can see from the results above, the statement in else is not executed when there is an exception in the try. In this way, we can find that if an exception occurs in the preceding statement, the subsequent statement does not need to continue, it can be placed in the else
Example 2:
def fetcher (obj, index): return obj[index]x = ' spam ' Try:print fetcher (x, 3) except Exception:print ' HHH ' else:print ' has no E Xception ' Print fetcher (x, 2) print '---' * 10try:print fetcher (x, 4) except Indexerror:print ' got exception ' Else:print ' has No exception ' Print Fetcher (x, 2)
The result is:
MHAs no Exceptiona------------------------------got Exceptiona
As you can see from the results above, if there is no else behind the except, the following statement will be executed regardless of whether there is an exception in the try
else role in Python exceptions