Re: Regarding exception handling
From: Bryan (belred_at_gmail.com)
Date: 01/31/05
- Next message: Dave Benjamin: "Nested scopes and class variables"
- Previous message: Baoqiu Cui: "a Python bug in processing __del__ method ??"
- In reply to: Dan Perl: "Re: Regarding exception handling"
- Next in thread: Aggelos I. Orfanakos: "Re: Regarding exception handling"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
To: python-list@python.org Date: Sun, 30 Jan 2005 22:53:40 -0800
Dan Perl wrote:
> "Bryan" <belred@gmail.com> wrote in message
> news:mailman.1614.1107137827.22381.python-list@python.org...
>
>>IMO, that is not the reason for the try/finally statement and it is not
>>redundant. the try/finally statement guarantees the resource is closed
>>and the try/finally statement only gets executed if and only if the
>>opening of the resource doesn't raise an exception. it has nothing to do
>>with exception handling.
>
>
> But IMO, try-finally is meant to be used only if the block in the try clause
> may raise exceptions. Here is an example that shows what I meant:
> s = ... # socket opens
> try:
> a = 1
> finally:
> s.close()
>
> works perfectly the same as:
> s = ... # socket opens
> a = 1
> s.close()
>
the above is not the same. make the a = ... raise an exception and you'll see
the difference.
s = ... #
a = 1/0
s.close()
as you can see, s.close() will never be called. also, in this example, i
intentionally didn't put the extra try/except around the try/finally statement.
usually i let an exception caused by s = ... to bubble up to some level that
knows how to handle that error. we are talking about a resource here and in my
experience, these low level functions (below the UI or management layer) don't
know how to or shouldn't handle resources that can't be opened.
bryan
> The try-finally statement does not "handle" the exception, but it makes
> sense only if exceptions are possible. There is no point in enclosing "a =
> 1" in any kind of try statement.
>
> According to a following posting from Angelos he did expect some other
> exceptions than socket.error and hence the nested try's. To my defence
> though, I put in a disclaimer for that case in my initial posting.
>
>
>>in the previous 2 examples s = ... was placed inside the try/finally, but
>>if an exception occures and s doesn't get bound to an object, then
>>s.close() in both examples will raise a NameError on s.
>
>
> That is a very good point. I missed it.
>
> Dan
>
>
- Next message: Dave Benjamin: "Nested scopes and class variables"
- Previous message: Baoqiu Cui: "a Python bug in processing __del__ method ??"
- In reply to: Dan Perl: "Re: Regarding exception handling"
- Next in thread: Aggelos I. Orfanakos: "Re: Regarding exception handling"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|