those darn exceptions

Chris Angelico rosuav at gmail.com
Mon Jun 20 23:19:09 EDT 2011


On Tue, Jun 21, 2011 at 11:43 AM, Chris Torek <nospam at torek.net> wrote:
> It can be pretty obvious.  For instance, the os.* modules raise
> OSError on errors.  The examples here are slightly silly until
> I reach the "real" code at the bottom, but perhaps one will get
> the point:
>
>    >>> import os
>    >>> os.kill(getpid(), 0) # am I alive?
>    >>> # yep, I am alive.
>    ...
>
> [I'm not sure why the interpreter wants more after my comment here.]
>

It's not wanting more. It responded to your statement "yep, I am
alive" by boggling at you. It said, and I quote, "...". What next?
Reading the obituaries column in search of your own PID?

Yep, slightly silly. And very amusing. But back to the serious:

os.kill(pid,0) doesn't work on Windows, but that just means this whole
function can't be used on Windows. (Actually, the kill call DOES work.
It just doesn't do what you want here... it kills the process.)

os.kill("asdf",0) --> TypeError: an integer is required
os.kill(-1,0) --> no error raised - not sure if you want to propagate
os.kill()'s behaviour on negative PIDs or not - see for instance
http://linux.die.net/man/2/kill

I'm not sure if it's possible to put Python into "secure computing"
mode (with prctl(PR_SET_SECCOMP) on Linux), but if you did, then
there'd be an additional possible result from this: No return at all,
because your process has just been killed for trying to kill someone
else. (Secure Computing: The death penalty for attempted murder.)

Interesting concept of pulling out all possible exceptions. Would be
theoretically possible to build a table that keeps track of them, but
automated tools may have problems:

a=5; b=7; c=12
d=1/(a+b-c) # This could throw ZeroDivisionError

if a+b>c:
  d=1/(a+b-c) # This can't, because it's guarded.
else:
  d=2

And don't tell me to rewrite that with try/except, because it's not the same :)

I'd be inclined to have comments about the exceptions that this can
itself produce, but if there's exceptions that come from illogical
arguments (like the TypeError above), then just ignore them and let
them propagate. If is_process("asdf") throws TypeError rather than
returning False, I would call that acceptable behaviour.

Chris Angelico



More information about the Python-list mailing list