Getting started with Python programming to Practice (iii)

Source: Internet
Author: User

1. Exceptions

Exceptions are handled using the TRY-EXCEPT code block. The try-except code block lets python perform the specified action and tells Python what to do if an exception occurs.

When you use the TRY-EXCEPT code block, the program continues to run even if an exception occurs: Displays the friendly error messages you wrote, not the traceback that confuse the user.

Print (5/0)
Traceback (most recent):  File "Exception_division", line 1, in <module>    print (5/0) Zerodivisionerror:division by Zero

The program is bad, let users see Traceback is not a good idea, malicious users will know your program's file name, you will also see some of the code does not run correctly.

Print("Give Me II Numbers,and I ' ll divide them.")Print("Enter ' Q ' to quit.") whileTrue:first_number=input ("\nfirst Number:")    ifFirst_number = ='Q':         BreakSecond_number=input ("Second Number:")    ifSecond_number = ='Q':         Break    Try: Answer=int (First_number)/Int (second_number)exceptZerodivisionerror:Print("You can ' t divide by 0!")    Else:        Print(answer)
Give Me II Numbers,and I ' ll divide them. Enter ' Q ' to quit. First Number:5second number:0you can ' t divide by 0! First Number:5second Number:22.5first number:q

In this way, the user sees a friendly error message, not a traceback.

Getting started with Python programming to Practice (iii)

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.