else role in Python exceptions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.