In the previous programming exercise, also said the exception many times, this blog simple to say that the exception.
Syntax for exception:
**try:
Detection Range
Except exception[as reason]:
Code resolved after an exception * *
(Be sure to pay attention to the alignment problem of indentation)
Here's a simple example:
As I said before, there is an exception to the file that does not exist when you open a nonexistent file by default, so let's take this as an example, I open a file that does not exist in the E disk by default.
F=open ("e:\\ Why I am a file. txt") print (F.read ()) F.close ()
Results The system will have an exception:
The following are the workarounds for the exception to modify the code:
Try: f=open ("Why am I a file. txt") print (F.read ()) f.close () except OSError: print ("The file is wrong!") ")
Try: f=open ("Why am I a file. txt") print (F.read ()) f.close () #except oserror:# Print ("The file is wrong! ") except OSError as reason: print (" The file is wrong \ n the reason for the error: "+str (reason)) finally: print (" The code that will be executed anyway, such as the close of the file ")
Exceptions can be handled in this way, and finally there is a finally statement, which executes regardless of whether an exception occurs.
In the end, simply say the execution of the try-except-finally statement:
We write the possible exception of the statement in the TRY statement, the program runs the first execution of the contents of the Try statement, if the exception occurs, after the execution of the try statement, will skip the except statement, if there is a finally statement, the execution of the finally statement, the program is completed. If an exception occurs in a try statement execution, a try statement is executed, the statement in except executes, and the finally statement is executed after the except statement is executed, or the program execution ends.
Above is the Python 0 basic Primer 12 exception content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!