mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-14 02:34:17 +02:00
Merge pull request #1223 from outcoldman/patch-2
Python3: add finally and with statements
This commit is contained in:
@@ -374,6 +374,13 @@ except (TypeError, NameError):
|
|||||||
pass # Multiple exceptions can be handled together, if required.
|
pass # Multiple exceptions can be handled together, if required.
|
||||||
else: # Optional clause to the try/except block. Must follow all except blocks
|
else: # Optional clause to the try/except block. Must follow all except blocks
|
||||||
print("All good!") # Runs only if the code in try raises no exceptions
|
print("All good!") # Runs only if the code in try raises no exceptions
|
||||||
|
finally: # Execute under all circumstances
|
||||||
|
print "We can clean up resources here"
|
||||||
|
|
||||||
|
# Instead of try/finally to cleanup resources you can use a with statement
|
||||||
|
with open("myfile.txt") as f:
|
||||||
|
for line in f:
|
||||||
|
print line
|
||||||
|
|
||||||
# Python offers a fundamental abstraction called the Iterable.
|
# Python offers a fundamental abstraction called the Iterable.
|
||||||
# An iterable is an object that can be treated as a sequence.
|
# An iterable is an object that can be treated as a sequence.
|
||||||
|
Reference in New Issue
Block a user