[Tutor] How to exit program without sys.exit()

Alan Gauld alan.gauld at btinternet.com
Thu Dec 18 02:26:13 CET 2008


"David" <david at abbottdavid.com> wrote

> put a couple together just to practice. I have heard it is not a 
> good idea to use sys.exit()

sys.exit is there to exit from a program so there is absolutely 
nothing
wrong with using it. However the way you are using it is not optimal.
A program will terminate or exit by itself if you allow it to "run off 
the end".
So you can remove most of your sys.exit() calls.

Where you want to use sys.exit() is where something happens that
would leave your program running but in a state where it might then do
some damage or produce a wriong result. You can then force a
premature exit with sys.exit. However even in these cases it's often
possible to restructure your code so that an explicit call to sys.exit
is not needed.

So to answer your question, using sys.exit is not bad or wrong,
but mostly you don't need to. It's better to reserve its use for 
occasions
where the program has to be forced to exit early. The other place 
where
you should use sys.exit() is where you want to return a specific error
code to the Operating System - usually for other scripts to use to 
detect
errors by your program.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list