Python exception handling--try except else raise finally

Source: Internet
Author: User
Tags for in range

An exception occurred while writing the program, and the program may not function correctly. In this case, you need to introduce exception handling

1.try ... except

Try to write the normal running program code, except is the exception condition

1 a=3 2 b=2 3 for in range (5):  4     try:  5         a = A-1 6         c=b/a  7         print(c) 8 9     except Exception as E: Ten         Print (e) #输出异常行为名称

The result is shown below, with the name of the exception behavior (division by zero)

2.try ..... except...else statement, when no exception occurs, the statement in else will be executed

A=3b=2 for in range (3):    try:        = A-1        C=b/ a         Print (c)     except Exception as E:         Print (e)     Else :         Print (" normal operation ")

When an exception occurs, the Else statement is not run

3.

when a try ... finally statement is executed , the statement in finally is executed, regardless of whether the exception occurred or not, until the end of the program.

#Author:wang YueA=3b=2 forIinchRange (3):    Try: A= A-1C=b/aPrint(c)exceptException as E:Print(e)Else:        Print("normal Operation")    finally:        Print("finally")

4.raise throws an exception, for example, when a condition does not satisfy the user's intention to throw an exception

A=3if a<4:    Exception
elseprint(a)

Python exception handling--try except else raise finally

Related Article

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.