Use try, cmdt, and else To make the Python program more "strong", using tpython

Source: Internet
Author: User

Use try, cmdt, and else To make the Python program more "strong", using tpython

In the executed program, fatal errors may occur due to some reasons, such as input and output (for example, the input file name is incorrect and the relevant Code cannot be run .). At this time, you do not want the program to be hung up directly, but simply display some information to make it end smoothly. In this case, you can use the try, try t, and else keywords to form an inclusive program.

 

Three keywords are explained separately:

Try

Statement t: if the statement in try cannot be correctly executed, execute the statement in statement T, which can be an error message or other executable statements.

Else: if the statements in try can be normally executed, execute the statements in else (equivalent to the program without encountering fatal errors)

 

We use an instance program to explain the usage of these three keywords:

# Coding: gbk
"Module documentation"
# Import
# Variable
# Class
# Function

If _ name _ = '_ main __':
Fname = raw_input ("Please input the file's name :")
Print fname

Try: # try to execute one or more statements
Fobj = open (fname, "r") # try to open a file
Handle t IOError, error: # If the statement in try cannot be executed, execute the statement in try t. Note that "error" is equivalent to a variable, used to store error messages
# Standard statements and related information.
Print "*** file open error", error

Else: # If the statements in try are successfully executed, execute the statements in else.
For eachline in fobj:
Print eachline,
Fobj. close ()

If the statement in try cannot be executed normally, the output result is:

Please input the file's name: s
S
* ** File open error [Errno 2] No such file or directory:'s'

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.