The purpose of exception handling is to prevent the user from seeing unfriendly exceptions and to avoid the program exiting unexpectedly.
I. Through try...except ... Intercept the exception to ensure that the program continues execution
Try:open (' Test.txt ', ' R ') 1/0except zerodivisionerror,e:print eprint ' done '
Run the above program directly throws an exception as follows, the statement after the 2nd line is not executed, the program exits directly
>>>
Traceback (most recent):
File "D:\Python\code\test.py", line 2, <module>
Open (' Test.txt ', ' R ')
IOError: [Errno 2] No such file or directory: ' Test.txt '
>>>
Next we'll run the two-line statement swap position of the try
try:1/0 open (' Test.txt ', ' R ') except Zerodivisionerror,e:print eprint ' done '
>>>
Integer division or modulo by zero
Done
>>>
You can see that done is printed and the exception is intercepted, ensuring that the program continues to execute
Two. Finally clause: Execute with or without exception, commonly used for file close, release operation of database connection
Try:1/1except zerodivisionerror,e:print efinally:print ' done '
>>>
Done
>>>
Program no exception still print out done
Three. Exception throws raise clause: actively throws an exception to the previous layer for API error handling, masking the underlying exception, etc.
Try:1/0except exception,e:print str (e) Raise Exception (' Test raise ')
>>>
Integer division or modulo by zero
Traceback (most recent):
File "D:\Python\code\test.py", line 5, <module>
Raise Exception (' Test raise ')
Exception:test Raise
>>>
This article from "Today's efforts, tomorrow's success!" "Blog, be sure to keep this provenance http://zhzhgo.blog.51cto.com/10497096/1676922
Python Exception handling