Python Exception handling

Source: Internet
Author: User
Tags integer division

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

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.