[Python-ideas] with statement vs. try...except...finally

Gerald Britton gerald.britton at gmail.com
Fri May 29 22:58:55 CEST 2009


Good point, so can this be translated to a "with" statement:
try:
 f = open('foo')
 try:
 line = f.readline()
 try:
 f.close()
 except IOError:
 line = "can't close"
 except IOError:
 line = "can't read"
except IOError:
 line = "can't open"
??
I guess I'm wondering if we need a with...except construct so that we
can get exceptions that happen after the with context is entered
without wrapping the with statement in try...except.
On Fri, May 29, 2009 at 3:49 PM, Pascal Chambon
<chambon.pascal at wanadoo.fr> wrote:
> Gerald Britton a écrit :
>>>> I'm wondering if the "with" statement should have exception clauses
>> like the "try" statement, even though this seems to defeat part of the
>> reason for the "with" statement.
>>>> Currently I have a program segment that opens a file and reads a line,
>> something like this (distilled to its elements for illustration):
>>>> try:
>>    f = open('foo')
>>    line = f.readline()
>>    f.close()
>> except IOError:
>>    line = 'default'
>>>> So that I get a default value if anything goes awry whilst reading the
>> file.
>>>> If I write it using a "with" statement, I might have:
>>>> line = 'default'
>> with open('foo') as f:
>>   line = f.readline()
>>>> Fine so far, but what if I want to be more granular?  e.g. with
>> "try...except":
>>>> try:
>>    f = open('foo')
>> except IOError:
>>    line = "can't open"
>>>> try:
>>    line = f.readline()
>> except IOError:
>>    line = "can't read"
>>>> try:
>>    f.close()
>> except IOError:
>>    line = "can't close"
>>>> I can't see how to replace the above try-triplet with a "with"
>> encapsulation. Or, do I have to wrap the "with" statement in try like
>> this:
>>>> try:
>>>>  with open('foo') as f:
>>     line = f.readline()
>>>> except IOError:
>>  line = 'problem with read or close"
>>>>>>>> I'd say the triplet of "try...except" clauses above isn't OK, because if the
> file opening fails, teh code will try anyway to read it and to close it,
> leading to nameError and other uncaught exception.
>> But the last clause, wrapped in try..except, seems fine to me.
>> ++
> Pascal
>>>>
-- 
Gerald Britton


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /