Handle SystemExit exception

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Feb 1 04:45:30 EST 2009


En Sun, 01 Feb 2009 07:27:26 -0200, asit <lipun4u at gmail.com> escribió:

> My program contains some sys.exit(1) and when its executed an
> exception known as SystemExit is thrown.

This is normal behaviour - but you should not "see" the SystemExit. Do you  
mean that a stack trace appears in the console?

> I tried to handle bu using following code snippet
>
> if __name__ == "__main__":
>     try:
>         main()  #main contains sys.exit(1)
>     except KeyboardInterrupt:
>         print "aborted by user"
>     except SystemExit:
>         pass
>
> But it does not work.

I've tested adding this:

def main():
   sys.exit(1)

and it exited normally, even after removing the SystemExit clause.

> Can anyone help me out ???
>
> Though KeyboradInterrupt is handled, but why SystemExit is not
> handles ????

Perhaps there is another try/except somewhere else that handles SystemExit?
Look for bare except clauses, like

try:
except: ...

They should *not* be used. With Python 2.5 and above, theh "catch-all"  
should be written as:

try:
except Exception: ...

If you are using 2.4 or earlier, should be:

try:
except (SystemExit, KeyboardInterrupt): raise
except: ...

-- 
Gabriel Genellina




More information about the Python-list mailing list