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 thetry
to run the code, and if the execution goes wrong, the subsequent code does not continue, but jumps directly to the error-handling code,except
statement block, execution finishedexcept
after that if therefinally
statement block, the executionfinally
statement 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