In the previous programming exercises, I have also said exceptions many times. this blog briefly talks about exceptions. In the previous programming exercises, I have also said exceptions many times. this blog briefly talks about exceptions.
Exception syntax:
** Try:
Detection scope
Failed T Exception [as reason]:
Code resolved after an exception occurs **
(Be sure to pay attention to the indentation alignment problem)
The following is a simple example:
As mentioned before, when a non-existing file is opened by default, the file does not exist. let's take this as an example. by default, I open a file that does not exist in an edisk.
F = open ("E: \ I am a file. txt") print (f. read () f. close ()
The result system has an exception:
The following code is modified according to the exception solution:
Try: f = open ("I am using a file. txt") print (f. read () f. close () using T OSError: print ("The file has an error! ")
Try: f = open ("I am using a file. txt") print (f. read () f. close () # exist T OSError: # print ("An error occurred in the file! ") Failed t OSError as reason: print (" file error \ n error cause: "+ str (reason) finally: print (" code executed in any case, for example, close the file ")
The exception can also be handled in this way. finally, there is a finally statement, which must be executed no matter the exception does not occur.
We will write the statements that may generate exceptions in the try Statement. when the program runs, we first execute the content contained in the try Statement. If no exception occurs, after the try statement is executed, the skip T statement will be skipped, if a finally statement exists, the finally statement is executed and the program execution is complete. If an exception occurs during the execution of the try statement, the try statement jumps out and runs the statement in limit T. after the limit T statement is executed, if a finally statement exists, the finally statement is executed. Otherwise, the execution of the program ends.
The above is the exception of Python. For more information, see PHP Chinese website (www.php1.cn )!