Lably
Skip to content

Graceful exit

Simple programming idiom in a program to detect and manage a serious error condition

  • 3 min read
  • 3 chapters

Related on Lably

Through Computer program, Error and Exception handling

Usually, code for a graceful exit exists when the alternative — allowing the error to go undetected and unhandled — would produce spurious errors or later anomalous behavior that would be more difficult for the programmer to debug. The code associated with a graceful exit may also take additional steps, such as closing files, to ensure that the program leaves data in a consistent, recoverable state.

Graceful exits are not always desired. In many cases, an outright crash can give the software developer the opportunity to attach a debugger or collect important information, such as a core dump or stack trace, to diagnose the root cause of the error.

In a language that supports formal exception handling, a graceful exit may be the final step in the handling of an exception. In other languages graceful exits can be implemented with additional statements at the locations of possible errors.

The phrase "graceful exit" has also been generalized to refer to letting go from a job or relationship in life that has ended.

In Perl

In the Perl programming language, graceful exits are generally implemented via the die operator. For example, the code for opening a file often reads like the following:

<span id="mwKg"></span><span class="c1" id="mwKw"># Open the file 'myresults' for writing, or die with an appropriate error message.</span> <span class="nb" id="mwLA">open</span><span class="w" id="mwLQ"> </span><span class="n" id="mwLg">RESULTS</span><span class="p" id="mwLw">,</span><span class="w" id="mwMA"> </span><span class="s" id="mwMQ">'>'</span><span class="p" id="mwMg">,</span><span class="w" id="mwMw"> </span><span class="s" id="mwNA">'myresults'</span><span class="w" id="mwNQ"> </span><span class="ow" id="mwNg">or</span><span class="w" id="mwNw"> </span><span class="nb" id="mwOA">die</span><span class="w" id="mwOQ"> </span><span class="s" id="mwOg">"can't write to 'myresults' file: $!"</span><span class="p" id="mwOw">;</span>

If the attempt to open the file myresults fails, the containing program will terminate with an error message and an exit status indicating abnormal termination.

Sign in to keep reading

2 more chapters are free with a Lably account.

More in From Lably lessons