Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #95162

Re: except block isn't catching exception

References <48587161-1bd6-47e4-b2c9-7a37c60a59e5@googlegroups.com> <mailman.1286.1438908366.3674.python-list@python.org> <c0684935-c807-4d98-9a04-8c2f7986169d@googlegroups.com> <CAPTjJmqVQ2xftm7rxg+co0bTyafU_iQaEMu9gPgD-39z1qCa_w@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2015-08-08 00:56 -0600
Subject Re: except block isn't catching exception
Newsgroups comp.lang.python
Message-ID <mailman.1330.1439017052.3674.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Aug 7, 2015 at 8:44 PM, Chris Angelico <rosuav@gmail.com> wrote:
> The exception isn't happening inside sock.accept(), as I explained. So
> you can't catch it there.

Where does the exception happen then? Your explanation only covered
why the blocking call cannot be interrupted by it, not why the
exception isn't simply raised when the blocking call finishes.

I played around with this and found that if the try...except chain is
wrapped in another outer try statement, then the KeyboardInterrupt
exception does get caught by the outer exception handler as one might
expect. For the inner try statement though, neither any except block
nor the else block is executed, just the finally block. I didn't know
until now that was even possible.

The language reference mentions this in regard to the try statement:

"""
If the evaluation of an expression in the header of an except clause
raises an exception, the original search for a handler is canceled and
a search starts for the new exception in the surrounding code and on
the call stack (it is treated as if the entire try statement raised
the exception).
"""

So my theory as to what's going on here is that sock.accept raises a
socket.timeout exception, but then the KeyboardInterrupt is raised
before the first except block even begins to check the exception type,
and so it's treated as if the "entire try statement" raised
KeyboardInterrupt. Hence it can't be caught there, but only in an
outer try statement.

Whatever the reason, it definitely seems to be an interesting corner case.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

except block isn't catching exception sohcahtoa82@gmail.com - 2015-08-06 17:34 -0700
  Re: except block isn't catching exception Chris Angelico <rosuav@gmail.com> - 2015-08-07 10:46 +1000
    Re: except block isn't catching exception sohcahtoa82@gmail.com - 2015-08-07 10:16 -0700
      Re: except block isn't catching exception Chris Angelico <rosuav@gmail.com> - 2015-08-08 12:44 +1000
      Re: except block isn't catching exception Ian Kelly <ian.g.kelly@gmail.com> - 2015-08-08 00:56 -0600
      Re: except block isn't catching exception Chris Angelico <rosuav@gmail.com> - 2015-08-08 17:08 +1000

csiph-web