3

I knew that sys.exit() raises an Exit exception, so when I run this I knew it wouldn't exit:

In [25]: try:
   ....:     sys.exit()
   ....: except:
   ....:     print "oops"
   ....:     
oops

But I thought that os._exit() was meant to exit using a C call, but it's also causing an exception:

In [28]: try:
   ....:     os._exit()
   ....: except:
   ....:     print "oops"
   ....:     
oops

Is there a way of doing this without killing the PID?

1
  • 1
    You should never use except without a specific exception. Commented Jun 5, 2012 at 16:08

2 Answers 2

9

I'm not sure I understand your question, but os._exit isn't raising an exception -- you calling os._exit with the wrong number of arguments is:

try:
    os._exit()
except Exception as e:
    print e

#output: _exit() takes exactly 1 argument (0 given)
Sign up to request clarification or add additional context in comments.

Comments

4

Don't use except without an Exception class, so sys.exit will just work fine without triggering the exception handling:

>>> import sys
>>> try:
...     sys.exit()
... except Exception:
...     print 'oops'
... 
$ 

There are other exceptions which are triggered with a plain except clause (and in general shouldn't), especially KeyboardInterrupt.

5 Comments

I know this is the conventional wisdom--and even more so, to use a narrowly-specified, specific exception. But when you're going to catch every exception and not going to use the exception data (e.g. contra @mgilson's answer), is there really any virtue in except Exception? Is there any non-Exception possibility that will trigger the except clause?
@ire_and_curses This does exit the process without triggering the exception handler.
@ms4py - I see. That's interesting! Vote redacted!
@JonathanEunice Please re-read my answer, it should be more clear now :)
Why do people lie over and over again? It is very easy to check that sys.exit() throws a SystemExit exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.