Killing your program quickly
exit and die!
Exit can be used to exit a program quickly but relatively correctly, passing a numeric exit value. Die will do the same thing but passes a numeric or text value which can be trapped as an exception (ie flagged as an error).
When and why
Sometimes you'll want to end your program quickly. To do this there is the ideal, right, way:
- You should have a semaphore that is checked in every loop and if statement of your program. If an event triggers a need to exit then each of these checks will allow the program to reverse it's journey thus far, coming straight back out of each control structure until there is nothing left but the end of the program. The down side of this is that it may involve many, many lines of extra code in a larger program.
The wrong way - generally - is to terminate or abort the program suddenly. Many modern languages provide at least one command for this. This does not do any tidy-up that may be required of the program, and may lead to memory leaks, files left open or other unexpected issues. In perl, use the command die to kill the program instantly raising an exception; or exit to, well, exit instantly.
But don't forget to ask yourself, if this is the wrong thing to do, why are there two separate ways to do this? Because this may be seen as the "wrong but right in the circumstances" way.
- Sometimes the player of your game presses 'q' for quit there's no need to hang about, close files or do any of that other socially-reponsible stuff. Then issue an exit(0) command to signal succesful/normal termination and rapidly close the app.
- Sometimes there is no way that the program can logically proceed. As an example, possibly the program has failed a sanity check. In this case, the die function is required to abort the program run without doing further damage. You can display a useful message as to why you are killing a program by enclosing that message after the die command as shown: die ("some useful message")
Last updated: 20120219-18:06