Handle SystemExit exception
Steven D'Aprano
steve at pearwood.info
Sun Feb 1 04:46:20 EST 2009
asit wrote:
> My program contains some sys.exit(1) and when its executed an
> exception known as SystemExit is thrown.
>
> 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.
It works for me:
>>> try:
... sys.exit()
... except SystemExit:
... pass
...
>>>
What does it do for you? Crash? Exit? print garbage to the screen?
I'm going to guess what you are doing. Do you have code like this?
try:
main() #main contains sys.exit(1)
except KeyboardInterrupt:
print "aborted by user"
except SomeOtherException, SystemExit:
pass
This will mask SystemExit and stop it from being caught. It should be
written like this:
except (SomeOtherException, SystemExit):
pass
Or possibly something like this?
try:
main() #main contains sys.exit(1)
except KeyboardInterrupt:
print "aborted by user"
except Exception:
do_something()
raise
except SystemExit:
pass
The Exception clause will catch SystemExit before the SystemExit clause will
see it. That should be written like this:
except SystemExit:
pass
except Exception:
do_something()
raise
--
Steven
More information about the Python-list
mailing list