Python learns-python2 in try: Finally and with. As

Source: Internet
Author: User

First, try...finally

high-level languages usually have a built-in set of try...except...finally... error-handling mechanism, Python is no exception.


when we think that some code might go wrong, you can use thetryto run the code, and if the execution goes wrong, the subsequent code does not continue, but jumps directly to the error-handling code,exceptstatement block, execution finishedexceptafter that if therefinallystatement block, the executionfinallystatement block, at this point, execution is complete.

As shown below:

Try:print ' Try ... ' r = 10/0print ' Result: ', rexcept zerodivisionerror, E:print ' except: ', efinally: print ' finally ... ' print ' END '

Second, with....as

This syntax is used instead of the traditional try...finally syntax.

With EXPRESSION [as VARIABLE] With-block

The basic idea is that the object with which the value is evaluated must have a __enter__ () method, a __exit__ () method.

Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS. The __exit__ () method of the previous return object is called when all code blocks following the with are executed.

File = Open ("/tmp/foo.txt") Try:data = File.read () finally:file.close ()

Use with AS as follows:

With open ("/tmp/foo.txt") as File:data = File.read ()


Python learns-python2 in try: Finally and with. As

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.