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'