Program termination: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (Emacs Lisp: Make code more idiomatic)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(16 intermediate revisions by 13 users not shown)
Line 13:
<br><br>
=={{header|11l}}==
<langsyntaxhighlight lang="11l">I problem
exit(1)</langsyntaxhighlight>
=={{header|6502 Assembly}}==
===Commodore 64, etc.===
This mostly depends on the hardware, but typically home computers would boot in BASIC and <code>JSR</code> to the starting address on the disk. This means that the return address for BASIC is on top of the stack, and an <code>RTS</code> instruction will exit the program and return to BASIC, provided that execution is not inside one of the disk's subroutines.
<langsyntaxhighlight lang="6502">;assuming this is not a subroutine and runs inline.
cmp TestValue ;a label for a memory address that contains some value we want to test the accumulator against
beq continue
rts ;unlike the Z80 there is no conditional return so we have to branch around the return instruction.
continue:</langsyntaxhighlight>
 
===Nintendo Entertainment System===
There is no firmware or BASIC to return to, so the easiest way to do this is to "trap" the program counter with a branch back to itself. This isn't a complete termination since NMI code will still run, unless you disable the screen. In order to display a static "THE END" screen that doesn't take user input, which is what many games did once the game was beaten, you can do this:
 
<langsyntaxhighlight lang="6502asm">sei ;disable IRQs
halt:
jmp halt ;trap the program counter</langsyntaxhighlight>
 
Of course, this depends on your game using a software abstraction of its screen data that gets written to the hardware ports during vBlank; since execution in the main program has halted the ports aren't getting any new data and instead the last thing written to their user ram counterparts is just getting written to the hardware ports over and over again.
Line 37:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program ending64.s */
Line 73:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
DO
IF Rand(0)=10 THEN
Line 84:
OD
PrintE("This is a dead code")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Program_termination.png Screenshot from Atari 8-bit computer]
Line 100:
 
However, this Rosetta Code task requires a simple stoppage of the program including all tasks. The simple way to achieve this is to abort the environment task.
<langsyntaxhighlight lang="ada">with Ada.Task_Identification; use Ada.Task_Identification;
 
procedure Main is
Line 109:
Abort_Task (Current_Task);
end if;
end Main;</langsyntaxhighlight>
Aborting a task with Abort_Task is equivalent to ''abort'' statement,
which is not used here because the environment task object is anonymous.
Line 127:
 
With the first approach:
<langsyntaxhighlight lang="ada">procedure Main is
-- Create as many task objects as your program needs
begin
Line 137:
return; -- actually, this is not needed
end if;
end Main;</langsyntaxhighlight>
A task might look like:
<langsyntaxhighlight lang="ada">task body Some_Task is
begin
loop
Line 152:
end select
end loop;
end Some_Task;</langsyntaxhighlight>
With the second approach one simply returns from Main and all tasks are terminated by selecting the terminate alternative. Such tasks might look like:
<langsyntaxhighlight lang="ada">task body Some_Task is
begin
loop
Line 163:
end select
end loop;
end Some_Task;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
f1(integer a)
{
Line 180:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
The label "stop" appears at the start of the <i>standard-postlude</i> and can be invoked to terminate any program.
<langsyntaxhighlight lang="algol68">IF problem = 1 THEN
stop
FI</langsyntaxhighlight>
The <i>standard-postlude</i> closes any opens files and basically wraps up execution.
 
=={{header|ALGOL W}}==
The program can be stopped by a false assertion.
<langsyntaxhighlight lang="algolw">if anErrorOccured then assert( false );</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 200:
The memory used belongs to the application running the script and is reclaimed automatically.
 
<langsyntaxhighlight lang="applescript"> if (someCondition) then error number -128</langsyntaxhighlight>
 
In a stay-open applet:
 
<langsyntaxhighlight lang="applescript">on idle -- A stay-open applet's 'idle' handler is called periodically while the applet remains open.
-- Some code, including:
if (someCondition) then
Line 212:
 
return 10 -- Number of seconds to the next call of this handler if the applet's still open.
end idle</langsyntaxhighlight>
 
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">
#!/usr/local/bin/apl --script --
 
Line 239:
 
main
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 256:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program ending.s */
Line 284:
swi 0 @ perform the system call Linux
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">problem: true
if problem -> exit</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">If (problem)
ExitApp</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Then Endif is entirely unnecessary, but it is good form.
<langsyntaxhighlight AutoItlang="autoit">If problem Then
Exit
Endif</langsyntaxhighlight>
 
=={{header|AWK}}==
An "exit"-statement aborts the current script,
optionally returning a status-code:
<syntaxhighlight lang ="awk">if(problem)exit 1</langsyntaxhighlight>
 
Before exiting, the END-block(s) are processed. <br>
An "exit" in an END-block causes an immediate exit:
<langsyntaxhighlight lang="awk"># usage: awk -f exittest.awk input.txt
BEGIN { print "# Exit-Test" }
 
Line 317:
END { if(problem) {print "!! Problem !!"; exit 2} }
END { print "# Lines read:", NR }
</syntaxhighlight>
</lang>
To compare, un/comment one of the lines #1 or #2:
{{in}}
Line 347:
=={{header|Axe}}==
The following example will force exit from any number of nested calls and loops:
<syntaxhighlight lang ="axe">Returnʳ</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic">if problem = 1 then
end
end if</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoft Applesoft BASICbasic">10 IF 1 THEN STOP</langsyntaxhighlight>
 
==={{header|BaCon}}===
No special cleanup routines are compiled in by default, but any functions registered via POSIX ''atexit'' and/or ''on_exit'' will be honoured. END can include a status code to be passed back to the invoking process.
<syntaxhighlight lang ="freebasic">IF TRUE THEN END 42</langsyntaxhighlight>
 
==={{header|BASIC256}}===
Line 366:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang IS="is-BASICbasic"> 100 IF CONDITION THEN STOP</langsyntaxhighlight>
 
==={{header|Locomotive Basic}}===
<syntaxhighlight lang ="locobasic">10 IF 1 THEN END</langsyntaxhighlight>
 
==={{header|uBasic/4tH}}===
The keywords <code>STOP</code> and <code>END</code> are aliases. They do the same thing. Any expression resulting in a non-zero value is evaluated as "True".
<syntaxhighlight lang="text">If 1 Then Stop
If 1 Then End</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
The ZX Spectrum has a STOP command, rather than an END command:
<langsyntaxhighlight lang="zxbasic">10 LET a = 1: LET b = 1
20 IF a = b THEN GO TO 9995
9995 STOP</langsyntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang ="dos">if condition exit</langsyntaxhighlight>
In Windows batch files this doesn't need to exit the program but instead can also just exit a subroutine. <code>exit /b</code> can also be used alternatively if a return value if desired.
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> IF condition% THEN QUIT</langsyntaxhighlight>
Only QUIT fully terminates the program. END and STOP stop execution and return control to the immediate-mode prompt; END closes all open files, but STOP does not.
 
=={{header|Befunge}}==
<syntaxhighlight lang ="bbcbasic">_@</langsyntaxhighlight>
The @ instruction ends the program. Some interpreters revert changes to the code (made by p) while others do not.
 
=={{header|BQN}}==
<code>•Exit</code> immediately terminates the running BQN process. If the argument is a valid return code (on Unix, an integer), it is returned; otherwise, the default return code (the one returned when the end of the program is reached) is used.
 
We can use a block to create a conditional exit. Here we exit if the script is given zero command line arguments:
<syntaxhighlight lang="bqn">{
0=≠•args ? •Exit 0;
•Show "has args"
}</syntaxhighlight>
 
=={{header|Bracmat}}==
Line 395 ⟶ 408:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
/* More "natural" way of ending the program: finish all work and return
from main() */
Line 412 ⟶ 425:
of codes are agreed upon.
*/
}</langsyntaxhighlight>
The <code>atexit()</code> function (also in <tt>stdlib.h</tt>) can be used to register functions to be run when the program exits. Registered functions will be called in the reverse order in which they were registered.
<langsyntaxhighlight lang="c">#include <stdlib.h>
 
if(problem){
abort();
}</langsyntaxhighlight>
Unlike <tt>exit()</tt>, <tt>abort()</tt> will not do any cleanup other than the normal OS one. Also, it may cause other actions like producing a core dump or starting a debugger.
 
To end not just the current process, but all processes in the same group, do <syntaxhighlight lang C="c">exit_group();</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">if (problem)
{
Environment.Exit(1);
}</langsyntaxhighlight>
 
=={{header|C++}}==
There are several ways to terminate a program. The following is mostly the same as in C:
<langsyntaxhighlight lang="cpp">#include <cstdlib>
 
void problem_occured()
{
std::exit(EXIT_FAILURE);
}</langsyntaxhighlight>
The argument is the return value passed to the operating system. Returning 0 or the EXIT_SUCCESS signals successful termination to the calling process, EXIT_FAILURE signals failure. The meaning of any other value is implementation defined.
 
On calling <tt>std::exit</tt>, all functions registered with std::atexit are called, and the destructors of all objects at namespace scope, as well as of all static objects already constructed, are called. However the destructors of automatic objects (i.e. local variables) are ''not'' called (and of course, objects allocated with new will not be destructed as well, except if one of the called destructors destroys them). Due to this inconsistency calling <tt>std::exit</tt> is often not a good idea.
<langsyntaxhighlight lang="cpp">#include <cstdlib>
 
void problem_occured()
{
std::abort();
}</langsyntaxhighlight>
Unlike <tt>std::exit</tt>, <tt>std::abort</tt> will not do any cleanup other than the normal OS one. Also, it may cause other actions like producing a core dump or starting a debugger.
<langsyntaxhighlight lang="cpp">#include <exception>
 
void problem_occured()
{
std::terminate();
}</langsyntaxhighlight>
The function <tt>std::terminate</tt> is what is automatically called when certain exception related failures happen. However it also can be called directly. By default it just calls abort, but unlike abort, its behaviour can be overridden with <tt>std::set_terminate</tt> (but it still must terminate the program in one way or anouther). Thererfore the amount of cleanup it does depends on whether it was overridden, and what the overridden function does.
 
Line 460 ⟶ 473:
{{trans|Java}}
The call <tt>System.exit</tt> does not finalize any objects by default. This default is to keep the program thread-safe. From the javadocs for the method to change this default: "may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock."
<langsyntaxhighlight lang="clojure">(if problem
(. System exit integerErrorCode))
;conventionally, error code 0 is the code for "OK",
; while anything else is an actual problem
;optionally: (-> Runtime (. getRuntime) (. exit integerErrorCode))
}</langsyntaxhighlight>
You can use <code>(-> Runtime (. getRuntime) (. addShutdownHook myThread))</code> to add threads which represent actions to be run when the program exits.
 
This one does not perform cleanup:
<langsyntaxhighlight lang="clojure">(if problem
(-> Runtime (. getRuntime) (. halt integerErrorCode)))
; conventionally, error code 0 is the code for "OK",
; while anything else is an actual problem
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
Terminating the program will cause all open files to be closed and control to be returned to the operating system. There are 2 ways to do this: <code>STOP RUN</code> and <code>GOBACK</code>.<br/>
<langsyntaxhighlight lang="cobol">IF problem
STOP RUN
END-IF</langsyntaxhighlight>
 
<code>GOBACK</code> was added in COBOL 2002, and will terminate the program if it is reached in the '''main''' program.
<langsyntaxhighlight lang="cobol">IF problem
GOBACK
END-IF</langsyntaxhighlight>
 
The ability to return a return code to the operating system is available for both of these statements as an extension in some compilers.
Line 490 ⟶ 503:
=={{header|Common Lisp}}==
Many Common Lisp implementations provide a function named <code>quit</code> or sometimes <code>exit</code> which will exit the Lisp system; its parameters and the package it is in vary, but here are some implementations' versions, with a Unix-style exit status argument, and a fallback:
<langsyntaxhighlight lang="lisp">(defun terminate (status)
#+sbcl ( sb-ext:quit :unix-status status) ; SBCL
#+ccl ( ccl:quit status) ; Clozure CL
Line 500 ⟶ 513:
#+gcl (common-lisp-user::bye status) ; GCL
#+ecl ( ext:quit status) ; ECL
(cl-user::quit)) ; Many implementations put QUIT in the sandbox CL-USER package.</langsyntaxhighlight>
There is no standard form because the Common Lisp standard does not assume the presence of an operating system outside of the Lisp environment to exit to.
 
Line 510 ⟶ 523:
=={{header|D}}==
The usual C functions are available, plus assert Errors and user defined Errors, and Exceptions.
<langsyntaxhighlight lang="d">import core.stdc.stdio, core.stdc.stdlib;
 
extern(C) void foo() nothrow {
Line 562 ⟶ 575:
//abort(); // Also this is allowed. Will not call foo, bar, spam.
exit(0);
}</langsyntaxhighlight>
{{out}}
<pre>spam at exit
Line 571 ⟶ 584:
 
=== Simple exit with D Runtime cleanup ===
<langsyntaxhighlight lang="d">import core.runtime, std.c.stdlib;
 
static ~this() {
Line 591 ⟶ 604:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Called on dexit
Line 597 ⟶ 610:
 
=={{header|DBL}}==
<syntaxhighlight lang DBL="dbl">IF (CONDITION) STOP</langsyntaxhighlight>
 
=={{header|Delphi}}/{{header|Pascal}}==
<syntaxhighlight lang Delphi="delphi">System.Halt;</langsyntaxhighlight>
or
<langsyntaxhighlight Delphilang="delphi">System.Halt(1); // Optional exit code</langsyntaxhighlight>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">[quit] true do?</syntaxhighlight>
 
=={{header|E}}==
Exit indicating successful completion:
<langsyntaxhighlight lang="e">if (true) {
interp.exitAtTop()
}</langsyntaxhighlight>
Exit indicating some problem:
<langsyntaxhighlight lang="e">if (true) {
interp.exitAtTop("because the task said so")
}</langsyntaxhighlight>
Both of these have the same effect with regard to cleanup as as reaching the end of the main program. [To do: Find out what effect that is.]
 
Line 619 ⟶ 635:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">if rcode != :ok, do: System.halt(1)</langsyntaxhighlight>
<langsyntaxhighlight lang="elixir">exit(:normal)
# or
exit(:shutdown)</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(when something
(kill-emacs))</langsyntaxhighlight>
 
Functions in <code>kill-emacs-hook</code> are called. (Except prior to Emacs 24 that hook was not run when in <code>-batch</code> mode.) The underlying C library <code>atexit()</code> handlers are called.
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^| I try to use the exit codes described at:
| https://github.com/openbsd/src/blob/master/include/sysexits.h
|^
int EX_SOFTWARE = 70 # internal software error
logic hasProblem = true
if hasProblem do exit EX_SOFTWARE end
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\ProgramTermination.emal
echo Exit Code is %errorlevel%
Exit Code is 70
</pre>
 
=={{header|Erlang}}==
;Polite:
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
if problem ->
exit(1).</langsyntaxhighlight>
 
;As soon as possible:
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
if problem ->
halt().</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
if condition then
Environment.Exit 1</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel system ;
 
t [ 0 exit ] when</langsyntaxhighlight>
When the <code>exit</code> word is called, first it runs the shutdown hooks, and then exits the Factor VM, passing along an exit code to the operating system. If an error occurs while running the shutdown hooks, the error is ignored and the exit code <code>255</code> is passed along.
 
You can add your own shutdown hooks like so:
 
<langsyntaxhighlight lang="factor">USING: init io ;
 
[ "Exiting Factor..." print flush ] "message" add-shutdown-hook</langsyntaxhighlight>
 
They are name/quotation pairs that are added to the associative mapping at the <code>shutdown-hooks</code> symbol in the <code>init</code> vocabulary.
Line 664 ⟶ 696:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">debug @
if QUIT \ quit back to the interpreter
else BYE \ exit forth environment completely (e.g. end of a Forth shell script)
then</langsyntaxhighlight>
 
=={{header|Fortran}}==
In Fortran <tt>STOP</tt> stops the execution of the ''main'' process and its "children" (tested with OpenMP; if using POSIX threads, I think the <tt>stop</tt> behaves almost like C <tt>exit</tt>). Allocated memory or any other resource except opened file (which are closed) is not cleaned up.
<langsyntaxhighlight lang="fortran">IF (condition) STOP [message]
! message is optional and is a character string.
! If present, the message is output to the standard output device.</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 684 ⟶ 716:
 
Here is a very simple example of the use of the 'End' statement:
<langsyntaxhighlight lang="freebasic">'FB 1.05.0 Win64 'endprog.bas'
 
Dim isError As Boolean = True
Line 694 ⟶ 726:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
After running the program, the Windows console will look something like this:
Line 704 ⟶ 736:
exit code is 1
</pre>
 
=={{header|FutureBasic}}==
Quick and dirty. Terminates everything.
<syntaxhighlight lang="futurebasic">
if condition then end
</syntaxhighlight>
 
=={{header|Gambas}}==
In a GUI environment
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim siCount As Short
 
Line 717 ⟶ 755:
Me.Close
 
End</langsyntaxhighlight>
 
In a CLI environment
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
 
Line 730 ⟶ 768:
Quit
 
End</langsyntaxhighlight>
 
=={{header|Gema}}==
Terminate with an error message and a non-zero status code if "Star Trek" is found in the input stream.
<langsyntaxhighlight lang="gema">Star Trek=@err{found a Star Trek reference\n}@abort</langsyntaxhighlight>
 
=={{header|Gnuplot}}==
<langsyntaxhighlight Gnuplotlang="gnuplot">problem=1
if (problem) {
exit gnuplot
}</langsyntaxhighlight>
 
The Gnuplot manual under "exit" notes that "any open output files may not be completed cleanly". (Does that mean output buffers not flushed?)
Line 749 ⟶ 787:
===Return statement===
Basically, a return statement executed from anywhere in main() terminates the program.
<langsyntaxhighlight lang="go">func main() {
if problem {
return
}
}</langsyntaxhighlight>
Deferred functions are run when the enclosing function returns, so in the example below, function <tt>paperwork</tt> is run.
This is the idiomatic mechanism for doing any kind of necessary cleanup.
Line 763 ⟶ 801:
 
Returns from functions other than main do not cause program termination. In particular, return from a goroutine simply terminates that one goroutine, and not the entire program.
<langsyntaxhighlight lang="go">package main
 
import (
Line 808 ⟶ 846:
func cleanup(rec *requiresExternalCleanup) {
fmt.Println(rec.id, "cleanup")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 828 ⟶ 866:
===Os.Exit===
Os.Exit causes its argument to be returned to the operating system as a program exit code. Unlike the return statement and runtime.Goexit, os.Exit exits promptly and does not run deferred functions.
<langsyntaxhighlight lang="go">func main() {
fmt.Println("main program start")
 
Line 840 ⟶ 878:
os.Exit(-1)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 855 ⟶ 893:
It does this only in the goroutine where panic was called.
Deferred functions in other goroutines are not run and if panicking goes unrecovered and the program terminates, all other goroutines are terminated abruptly.
<langsyntaxhighlight lang="go">func pcj() {
fmt.Println("at the junction")
defer func() {
Line 871 ⟶ 909:
time.Sleep(1e9)
fmt.Println("main program done")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 885 ⟶ 923:
 
Solution #1:
<langsyntaxhighlight lang="groovy">if (problem) System.exit(intExitCode)</langsyntaxhighlight>
 
Solution #1:
<langsyntaxhighlight lang="groovy">if (problem) Runtime.runtime.halt(intExitCode)</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang ="qbasic">10 IF 1 THEN STOP</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad
import System.Exit
 
Line 901 ⟶ 939:
exitWith (ExitFailure integerErrorCode) -- some failure with code
exitSuccess -- success; in GHC 6.10+
exitFailure -- generic failure</langsyntaxhighlight>
The above shows how to exit a thread. When the main thread exits, all other threads exit, and the return code in the exit call is the return code of the program. When any thread other than the main thread exits, only it is stopped, and if the exit code is not ExitSuccess, it is printed.
 
=={{header|HicEst}}==
<syntaxhighlight lang HicEst="hicest">ALARM( 999 )</langsyntaxhighlight>
This closes windows, dialogs, files, DLLs, and frees allocated memory. Script editing is resumed on next start.
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">exit(i) # terminates the program setting an exit code of i
stop(x1,x2,..) # terminates the program writing out x1,..; if any xi is a file writing switches to that file
runerr(i,x) # terminates the program with run time error 'i' for value 'x'</langsyntaxhighlight>
 
=={{header|J}}==
Line 917 ⟶ 955:
 
Tacit version:
<syntaxhighlight lang ="j">2!:55^:] condition</langsyntaxhighlight>
Explicit version:
<langsyntaxhighlight lang="j">3 : 'if. 0~: condition do. 2!:55 condition end.'</langsyntaxhighlight>
 
=={{header|Java}}==
The call <tt>System.exit</tt> does not finalize any objects by default.
This default is to keep the program thread-safe. From the javadocs for the method to change this default: "may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock."
<langsyntaxhighlight lang="java">if(problem){
System.exit(integerErrorCode);
//conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
//optionally: Runtime.getRuntime().exit(integerErrorCode);
}</langsyntaxhighlight>
You can use <code>Runtime.getRuntime().addShutdownHook(myThread);</code> to add threads which represent actions to be run when the program exits.
 
This one does not perform cleanup:
<langsyntaxhighlight lang="java">if(problem){
Runtime.getRuntime().halt(integerErrorCode);
//conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|SpiderMonkey}}
The <code>quit()</code> function exits the shell.
<langsyntaxhighlight lang="javascript">if (some_condition)
quit();</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">[true] [quit] [] ifte.</syntaxhighlight>
 
=={{header|jq}}==
Line 949 ⟶ 990:
 
'''Example:'''
<langsyntaxhighlight lang="sh">$ jq -n '"Hello", if 1 then error else 2 end'
"Hello"</langsyntaxhighlight>
 
Note that error/0 expects its input to be null (as above), in which case no error message is printed, or a string, in which case the string is printed as an error message, as illustrated below:
<langsyntaxhighlight lang="sh">$ jq -n '"Hello" | if 1 then error else 2 end'
jq: error: Hello</langsyntaxhighlight>
 
=={{header|Jsish}}==
Line 965 ⟶ 1,006:
In ''jsish'' Ctrl-C will halt any running code and return to the shell. If no code is running, the shell exits on Ctrl-C.
 
<langsyntaxhighlight lang="javascript">assert(0 == 1);
 
if (problem) exit(1);</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
quit() # terminates program normally, with its child processes. See also exit(0).
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 981 ⟶ 1,022:
2. Uninvoked finalizers would then be invoked if this behavior had been enabled using the Runtime.runFinalizersOnExit(true) method. However, this method is currently deprecated because it may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, leading to erratic behavior or even deadlock.
 
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 987 ⟶ 1,028:
if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem
println("Program terminating normally") // this line will not be executed
}</langsyntaxhighlight>
After the program has terminated, the exit status can be queried from the command line (Windows 10) as follows:
{{out}}
Line 997 ⟶ 1,038:
=={{header|Lasso}}==
Lasso will stop processing when it encounters an "abort". By providing a "handle" block, possible cleanups can be executed before finishing execution.
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
//[
 
Line 1,008 ⟶ 1,049:
abort
 
stdoutnl('Ending execution')</langsyntaxhighlight>
 
{{out}}
Line 1,016 ⟶ 1,057:
 
It is also possible to provide a "handle" block that will only execute if there's an error.
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
handle_error => {
Line 1,027 ⟶ 1,068:
0/0
 
stdoutnl('Ending execution')</langsyntaxhighlight>
 
{{out}}
Line 1,040 ⟶ 1,081:
 
The following is functional. Better practice is to instead jump to commands or subs to close known open files, windows etc, avoiding error messages as above.
<langsyntaxhighlight lang="lb">if 2 =2 then end</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">bye ; exits to shell
 
throw "toplevel ; exits to interactive prompt
 
pause ; escapes to interactive prompt for debugging
continue ; resumes after a PAUSE</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">if some_condition then
os.exit( number )
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,069 ⟶ 1,110:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
For i=1 to 200
Line 1,087 ⟶ 1,128:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">beginning
define(`problem',1)
ifelse(problem,1,`m4exit(1)')
ending</langsyntaxhighlight>
{{out}}
<pre>
Line 1,100 ⟶ 1,141:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang Mathematica="mathematica">If[problem, Abort[]];</langsyntaxhighlight>
Kernels stop all computation after "Abort[]" command. But the kernels are still operational, and all definitions are still available. Note that an Abort[] can be caught by a calling function using <code>CheckAbort</code>, in which case the computation will continue at that place.
<pre>
Line 1,108 ⟶ 1,149:
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang="matlab">if condition
return
end</langsyntaxhighlight>
There is no special way to stop a program. You can terminate it by calling <code>return</code>.
<langsyntaxhighlight lang="matlab">if condition
quit
end</langsyntaxhighlight>
The <code>quit</code> function runs the MATLAB script <code>finish.m</code>, if it exists, and terminates MATLAB completely.
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Basically, it's simply quit() */
 
block([ans], loop, if (ans: read("Really quit ? (y, n)")) = 'y
then quit()
elseif ans = 'n then (print("Nice choice!"), 'done)
else (print("I dont' understand..."), go(loop)));</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">ИП0 x=0 04 С/П ...</langsyntaxhighlight>
 
Condition of termination is ''Р0 = 0''.
Line 1,132 ⟶ 1,173:
=={{header|Nanoquery}}==
Nanoquery supports both an exit statement and an exit function. The following lines are identical:
<syntaxhighlight lang="nanoquery">exit
<lang Nanoquery>exit
exit(0)</langsyntaxhighlight>
A value passed to the exit() function will be returned to the operating system after the program is halted.
 
Line 1,139 ⟶ 1,180:
Neko installs abnormal run down handlers, or can call the C ABI exit routine, which returns a status code to the operating system.
 
<syntaxhighlight lang="actionscript">/*
<lang ActionScript>/*
Program termination, in Neko
*/
Line 1,148 ⟶ 1,189:
if true sys_exit(return_code)
 
$print("Control flow does not make it this far")</langsyntaxhighlight>
 
{{out}}
Line 1,157 ⟶ 1,198:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System.Environment
...
when (problem) Exit(1)
...</langsyntaxhighlight>
 
=={{header|NetRexx}}==
NetRexx's <tt>exit</tt> statement invokes [[Java|Java's]] <tt>System.exit()</tt> so job termination is handled in the same way as any other Java program. (See [[#Java|Java]] above.)
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,173 ⟶ 1,214:
 
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">if problem1:
quit QuitFailure
 
if problem2:
quit "There is a problem", QuitFailure</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
IF problem THEN
HALT(1)
END
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
The code below, will terminate a program without any cleanup.
<langsyntaxhighlight lang="objeck">if(problem) {
Runtime->Exit(1);
};</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">if problem then
exit integerErrorCode;
(* conventionally, error code 0 is the code for "OK",
while anything else is an actual problem *)</langsyntaxhighlight>
The <code>at_exit</code> function can be used to register functions to be run when the program exits. Registered functions will be called in the reverse order in which they were registered.
 
Line 1,206 ⟶ 1,247:
OS.exit returns to OS with return value as parameter.
 
<langsyntaxhighlight Oforthlang="oforth">import: os
 
some_condition ifTrue: [ 0 OS.exit ]</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(shutdown 0) ; it can be any exit code instead of provided 0
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">if Problem then {Application.exit 0} end</langsyntaxhighlight>
All threads exit. All processes (local and remote) exit unless they were created with <code>detach:true</code>. Finalizers are not executed (unless enforced with <code>{System.gcDo})</code>.
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">if(stuff, quit)</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Extended Pascal}}
Extended Pascal (ISO standard 10206) defines a (parameter-less) <tt>procedure</tt> <tt>halt</tt>.
UCSD Pascal’s <tt>halt</tt> takes one <tt>integer</tt> argument (cf.&nbsp;[[#Delphi|Delphi]]).
<syntaxhighlight lang="pascal">if true then
begin
halt
end</syntaxhighlight>All regular cleanup procedures apply, nothing special.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">if ($problem) {
exit integerErrorCode;
# conventionally, error code 0 is the code for "OK"
# (you can also omit the argument in this case)
# while anything else is an actual problem
}</langsyntaxhighlight>
 
The <code>DESTROY()</code> methods of all objects are called, in an unspecified order (see "Global Destruction" in <code>perlobj.pod</code>). This includes objects in global variables or with circular references which otherwise keep them alive during normal running.
Line 1,240 ⟶ 1,290:
=={{header|Phix}}==
To terminate the entire application:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>if error_code!=NO_ERROR then
<span style="color: #008080;">if</span> <span style="color: #000000;">error_code</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">NO_ERROR</span> <span style="color: #008080;">then</span>
abort(0)
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
end if</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
To terminate just the current thread:
<!--</syntaxhighlight>-->
<lang Phix>if error_code!=NO_ERROR then
To terminate just the current thread (no threads under pwa/p2js though):
exit_thread(0)
<!--<syntaxhighlight lang="phix">-->
end if</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">error_code</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">NO_ERROR</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">exit_thread</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
Files will be closed automatically and memory will be freed, however any other cleanup should be invoked manually.<br>
Most of my code has Abort() routines acting as wrappers for final-housekeeping-then-abort().
 
=={{header|Phixmonti}}==
<syntaxhighlight lang Phixmonti="phixmonti">if 1 quit endif</langsyntaxhighlight>
See Phix commments.
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">if (problem)
exit(1);</langsyntaxhighlight>
The <code>register_shutdown_function()</code> function can be used to register functions to be run when the program exits.
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">
% ...
if problem then
halt
end,
% ...
</syntaxhighlight>
 
or
<syntaxhighlight lang="picat">
% ...
if problem then
exit
end,
% ...
</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
Line 1,263 ⟶ 1,336:
 
This will execute all pending 'finally' expressions, close all open files and/or pipes, flush standard output, and execute all expressions in the global variable '*Bye' before exiting.
<langsyntaxhighlight PicoLisplang="picolisp">(push '*Bye '(prinl "Goodbye world!"))
(bye)</langsyntaxhighlight>
{{out}}
<pre>Goodbye world!
Line 1,270 ⟶ 1,343:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">STOP; /* terminates the entire program */
/* PL/I does any required cleanup, such as closing files. */</langsyntaxhighlight>
<langsyntaxhighlight lang="pli">STOP THREAD (tiger); /* terminates only thread "tiger". */</langsyntaxhighlight>
<langsyntaxhighlight lang="pli">SIGNAL FINISH; /* terminates the entire program. */
/* PL/I does any required cleanup, */
/* such as closing files. */</langsyntaxhighlight>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">if condition then
sysexit();
endif;</langsyntaxhighlight>
 
=={{header|PostScript}}==
There are two ways which differ slightly:
<syntaxhighlight lang ="postscript">condition {stop} if</langsyntaxhighlight>
will terminate a so-called <code>stopped</code> context which is a way of executing a block of code and catching errors that occur within. Any user program will always run in such a context and therefore be terminated upon calling <code>stop</code>
 
Neither the operand stack nor the dictionary stack are touched or cleaned up when calling <code>stop</code>. Anything pushed onto either stack will remain there afterwards.
<syntaxhighlight lang ="postscript">condition {quit} if</langsyntaxhighlight>
will terminate the PostScript interpreter. This is definitely a way to stop the current program but since an interpreter can run multiple programs at the same time, this should rarely, if ever, be used.
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">if (somecondition) {
exit
}</langsyntaxhighlight>
This ends the scope for any non-global variables defined in the script. No special cleanup is performed.
 
=={{header|Prolog}}==
Terminate Prolog execution. Open files are closed. Exits the Interpreter.
<syntaxhighlight lang ="prolog">halt.</langsyntaxhighlight>
Terminate Prolog execution but don't exit the Interpreter.
<syntaxhighlight lang ="prolog">abort.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
This will free any allocated memory, close files and free other resources (i.e. windows, gadgets, threads, space for variable, etc.) that were set aside during execution of any PureBasic commands in the program.
<langsyntaxhighlight PureBasiclang="purebasic">If problem = 1
End
EndIf</langsyntaxhighlight>
It is possible to also access outside resources (i.e. via an OS API or linked library), and those items may or may not be cleaned up properly.
 
=={{header|Python}}==
;Polite:
<langsyntaxhighlight lang="python">import sys
if problem:
sys.exit(1)</langsyntaxhighlight>
The [http://docs.python.org/library/atexit.html atexit] module allows you to register functions to be run when the program exits.
;As soon as possible:
(Signals the underlying OS to abort the program. No cleanup is performed)
<langsyntaxhighlight lang="python">import os
if problem:
os.abort()</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<code>out!</code> will cleanly exit Quackery and return control to the calling program. This is demonstrated in the Quackery shell. When <code>10 random</code> returns <code>0</code> Quackery (which in this implementation is a function called from Python3) returns control to Python, which then terminates in the usual fashion and returns control to the zsh, from which we show this to be the case and then re-enter Quackery.
 
<syntaxhighlight lang="Quackery"> [ return$ nest$ size 2 / ]bailby[ ] is out! ( --> )</syntaxhighlight>
 
{{out}}
 
<pre>/O> [ 10 random dup
... iff
... [ echo cr ]
... else
... [ say "Bye-ee!" cr
... drop out! ]
... again ]
...
5
2
5
Bye-ee!
$ echo "$SHELL"
/bin/zsh
$ quackery
 
Welcome to Quackery
 
Enter "leave" to leave the shell.
 
Building extensions.
 
/O> </pre>
 
=={{header|QB64}}==
Line 1,328 ⟶ 1,433:
2) STOP - The program will close immediately, but will not close any open files. STOP is ONLY used for debugging purposes and should not be used to exit programs!<br>
3) SYSTEM - The ONLY proper command to immediately close a program in QB64 without a pause or interactive message as in the case with the END command.<br>
<langsyntaxhighlight lang="qbasic">INPUT "Press any key...", a$
IF 1 THEN SYSTEM</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">if(problem) q(status=10)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,339 ⟶ 1,444:
process, possibly returning a status code.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(run-stuff)
(when (something-bad-happened) (exit 1))
</syntaxhighlight>
</lang>
 
In addition, Racket has "custodians", which are objects that are used to
Line 1,353 ⟶ 1,458:
its client interaction is done. For example:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(parameterize ([current-custodian (make-custodian)])
Line 1,362 ⟶ 1,467:
;; like file ports, network connections, etc
(custodian-shutdown-all (current-custodian)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>if $problem { exit $error-code }</langsyntaxhighlight>
An <tt>exit</tt> runs all appropriate scope-leaving blocks such as <tt>LEAVE</tt>, <tt>KEEP</tt>, or <tt>UNDO</tt>,
followed by all <tt>END</tt> blocks, followed by all destructors that do more than just reclaim memory, and so cannot be skipped because they may have side effects visible outside the process. If run from an embedded interpreter, all
Line 1,373 ⟶ 1,478:
=={{header|REBOL}}==
The '''quit''' word stops all evaluation, releases operating system resources and exits the interpreter.
<langsyntaxhighlight REBOLlang="rebol">if error? try [6 / 0] [quit]</langsyntaxhighlight>
A return value can be provided to the operating system:
<langsyntaxhighlight REBOLlang="rebol">if error? try [dangerous-operation] [quit/return -12]</langsyntaxhighlight>
Because of REBOL's tightly integrated REPL, you can also use '''q''' to do the same thing.
<langsyntaxhighlight REBOLlang="rebol">if error? try [something-silly] [q/return -12]</langsyntaxhighlight>
Since GUI programs are often developed from the REPL, a special '''halt''' word is provided to kill the GUI and return to the REPL. No cleanup is done and the GUI is still displayed (although halted). You can restart it with the '''do-events''' word.
<langsyntaxhighlight REBOLlang="rebol">view layout [button "stopme" [halt]]</langsyntaxhighlight>
 
=={{header|Retro}}==
<syntaxhighlight lang Retro="retro">problem? [ bye ] if</langsyntaxhighlight>
 
=={{header|REXX}}==
In REXX, the REXX interpreter takes care of the closing of any open files (or any I/O streams), as well as any memory management (cleanup).
<langsyntaxhighlight lang="rexx">/*REXX program showing five ways to perform a REXX program termination. */
 
/*─────1st way────────────────────────────────────────────────────────*/
Line 1,414 ⟶ 1,519:
/* │ */ /*terminated. */
/* ↓ */
/* e-o-f */ /* e-o-f = end-of-file. */</langsyntaxhighlight>
 
Regina actually implies a RETURN when the end of the program is found at the end of a subroutine:
<langsyntaxhighlight lang="rexx">Parse Version v
Say v
Call sub
Say 'Back from sub'
Exit
sub:</langsyntaxhighlight>
{{out}}
<pre>REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015
Line 1,428 ⟶ 1,533:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for n = 1 to 10
see n + nl
if n = 5 exit ok
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
There are 2 ways of terminating a program in RPL.
'''IF''' problem '''THEN''' HALT '''END'''
Here, nothing is cleaned up: local variables are still existing and a step-by-step execution is possible thanks to the <code>SST</code> instruction, typically for debugging. Once the bug found, a manual cleanup must be done through the <code>KILL</code> instruction.
If a full termination with cleanup is desired, it must be written:
'''IF''' problem '''THEN''' ABORT '''END'''
All currently running processes are then terminated, all local variables are discarded and control is given back to the user.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">if problem
exit(1)
end
Line 1,443 ⟶ 1,556:
if problem
abort # equivalent to exit(1)
end</langsyntaxhighlight>
 
You can use <code>at_exit { ... }</code> to register a block of code which will be run when the program exits. Registered handlers will be called in the reverse order in which they were registered.
 
<langsyntaxhighlight lang="ruby">if problem
exit! # default value 1
end</langsyntaxhighlight>
Exits the process immediately. No exit handlers are run.
<code>exit!</code> is different from <code>exit</code> and it doesn't do an exception handling.
 
=={{header|Run BASIC}}==
<syntaxhighlight lang ="runbasic">if whatever then end</langsyntaxhighlight>
 
=={{header|Rust}}==
===Return statement===
A return statement executed in the main() function will exit the program.
<langsyntaxhighlight lang="rust">fn main() {
println!("The program is running");
return;
println!("This line won't be printed");
}</langsyntaxhighlight>
 
===Exit function===
You can run <code>std::process::exit</code> from anywhere in the program in order to exit. This will work from the main function as well as any other function or file.
 
<langsyntaxhighlight lang="rust">fn main() {
if problem {
std::process::exit(1); // 1 is the exit code
}
}</langsyntaxhighlight>
 
===Panics===
A panic in Rust will terminate the current thread. If the panic is in the main thread, the program will exit. If the panic is from another thread; that thread will terminate and the program, along with the other threads, will keep running.
 
<langsyntaxhighlight lang="rust">fn main() {
println!("The program is running");
panic!("A runtime panic occured");
println!("This line won't be printed");
}</langsyntaxhighlight>
Because of the panic, the last line will not run. If the panic happened in another thread, the program could keep running.
 
'''Panic Inside a Thread'''
<langsyntaxhighlight lang="rust">use std::thread;
 
fn main() {
Line 1,496 ⟶ 1,609:
 
println!("This line should be printed");
}</langsyntaxhighlight>
Now the panic will be contained inside the background thread and will not affect the rest of the program.
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">if (problem) {
// sys.exit returns type "Nothing"
sys.exit(0)
Line 1,507 ⟶ 1,620:
// while anything else is an actual problem
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
{{works with|Scheme|R<sup>6</sup>RS}}
<langsyntaxhighlight lang="scheme">(if problem
(exit)) ; exit successfully</langsyntaxhighlight>
or
<langsyntaxhighlight lang="scheme">(if problem
(exit #f)) ; exit unsuccessfully</langsyntaxhighlight>
or
<langsyntaxhighlight lang="scheme">(if problem
(exit some-value)) ; converts "some-value" into an appropriate exit code for your system</langsyntaxhighlight>
 
=={{header|Seed7}}==
When a program is stopped with exit(PROGRAM) allocated memory is freed and open files are closed,
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 1,530 ⟶ 1,643:
exit(PROGRAM);
end if;
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
The '''exit all''' command halts execution. Open files, sockets, database connections, etc. are closed and allocated memory is freed.
<langsyntaxhighlight lang="sensetalk">
if problemCondition then exit all
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">if (problem) {
Sys.exit(code);
}</langsyntaxhighlight>
 
=={{header|Simula}}==
<syntaxhighlight lang Simula="simula">IF terminallyIll THEN terminate_program;</langsyntaxhighlight>»The procedure "terminate_program" terminates program execution. It&nbsp;closes SYSIN&nbsp;and&nbsp;SYSOUT.
&nbsp;&nbsp;It is implementation-dependent with respect to whether or not other open files are also closed.« [[http://simula67.at.ifi.uio.no/Standard-86/chap_10.htm| Simula Standard 86]]
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">problem ifTrue: [exit: 1].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 1,557 ⟶ 1,670:
as the exit status of the program,
and the :s( ) goto transfers control to END.
<langsyntaxhighlight SNOBOL4lang="snobol4"> &code = condition errlevel :s(end)</langsyntaxhighlight>
 
=={{header|SSEM}}==
The machine can be halted at any point using a <tt>111 Stop</tt> instruction. Since the only conditional operation we have is <tt>011 Test</tt>, which has the effect of skipping one word if the number in the accumulator is negative, we had better illustrate it using that.
<langsyntaxhighlight lang="ssem">00000000000000110000000000000000 Test
00000000000001110000000000000000 Stop</langsyntaxhighlight>
This code fragment stops the computer if the accumulator is positive or zero; if it is negative, the <tt>Stop</tt> instruction is skipped and execution continues from the next instruction.
 
=={{header|Standard ML}}==
No cleanup is performed.
<langsyntaxhighlight lang="sml">if problem then
OS.Process.exit OS.Process.failure
(* valid status codes include OS.Process.success and OS.Process.failure *)
else
()</langsyntaxhighlight>
The <code>OS.Process.atExit</code> function can be used
to register functions to be run when the program exits.
Line 1,581 ⟶ 1,694:
At the script level, all that is needed to make the program terminate
is the <tt>exit</tt> command:
<langsyntaxhighlight lang="tcl">if {$problem} {
# Print a “friendly” message...
puts stderr "some problem occurred"
# Indicate to the caller of the program that there was a problem
exit 1
}</langsyntaxhighlight>
Alternatively, in a top-level script but ''not'' an event handler:
<langsyntaxhighlight lang="tcl">if {$problem} {
error "some problem occurred"
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 1,600 ⟶ 1,713:
 
=={{header|TI-89 BASIC}}==
<langsyntaxhighlight lang="ti89b">Prgm
...
Stop
...
EndPrgm</langsyntaxhighlight>
 
=={{header|Tiny BASIC}}==
You can either halt the program directly within the conditional...
<langsyntaxhighlight lang="tinybasic"> LET I = 0
10 IF I = 10 THEN END
LET I = I + 1
PRINT I
GOTO 10</langsyntaxhighlight>
 
...or allow it to fall through to the end of the program.
 
<langsyntaxhighlight lang="tinybasic"> LET I = 0
10 LET I = I + 1
PRINT I
IF I < 10 THEN GOTO 10</langsyntaxhighlight>
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">
(if errorCode
(exit errorCode))
</syntaxhighlight>
</lang>
 
=={{header|True BASIC}}==
Line 1,631 ⟶ 1,744:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
IF (condition==1) STOP
-> execution stops and message:
IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP "</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">#!/bin/sh
 
a='1'
Line 1,645 ⟶ 1,758:
exit 239 # Unexpected error
fi
exit 0 # Program terminated normally</langsyntaxhighlight>
 
=={{header|Unlambda}}==
<syntaxhighlight lang ="unlambda">`ei</langsyntaxhighlight>
Note: the argument to the <code>e</code> function is the return value of the program; however many implementation simply ignore it.
 
Line 1,655 ⟶ 1,768:
=={{header|Ursa}}==
Standard Ursa supports the stop function, which immediately halts program execution.
<syntaxhighlight lang ="ursa">stop</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">'In case of problem this will terminate the program (without cleanup):
If problem then End
'As VBA is run within an application, such as Excel, a more rigorous way would be:
If problem then Application.Quit
'This will stop the application, but will prompt you to save work.</langsyntaxhighlight>
 
=={{header|VBScript}}==
No matter how deep you're in, <code>wscript.quit</code> will get you out.
<langsyntaxhighlight lang="vb">dim i, j
j = 0
do
Line 1,676 ⟶ 1,789:
wend
next
loop</langsyntaxhighlight>
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">if (#99 == 1) { Return } // Exit current macro. Return to calling macro.
if (#99 == 2) { Break_Out() } // Stop all macro execution and return to command mode.
if (#99 == 3) { Exit } // Exit Vedit. Prompt for saving any changed files.
if (#99 == 4) { Exit(4) } // As above, but return specified value (instead of 0) to OS
if (#99 == 5) { Xall } // Exit Vedit. Save changed files without prompting.
if (#99 == 6) { Qall } // Exit Vedit. Do not save any files.</langsyntaxhighlight>
Return or Break_Out() do not perform any cleanup. If needed, cleanup has to be done in the macro before exit.
Special ''locked-in macro'' can be used to perform cleanup in case user presses Break key.
Line 1,696 ⟶ 1,809:
 
When the app needs to end, for whatever reason, problem or not, it's always a good idea to unload the forms ''first''.
<langsyntaxhighlight lang="vb">Sub Main()
'...
If problem Then
Line 1,705 ⟶ 1,818:
End If
'...
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
for num in 1..10 {
println('$num')
if num == 5 {exit(1)}
}
</syntaxhighlight>
 
{{out}}
<pre>
Process started >>>
1
2
3
4
5
<<< Process finished (Exit code 1)
</pre>
 
=={{header|Wren}}==
Line 1,721 ⟶ 1,853:
 
The following example illustrates the use of Fiber.suspend in a Wren CLI script.
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin, Stdout
 
System.write("Do you want to terminate the program y/n ? ")
Line 1,730 ⟶ 1,862:
Fiber.suspend() // return to OS
}
System.print("OK, carrying on")</langsyntaxhighlight>
 
{{out}}
<pre>
$ wren_cli program_terminationProgram_termination.wren
Do you want to terminate the program y/n ? y
OK, shutting down
Line 1,751 ⟶ 1,883:
change the commands the batch file executes.
 
<langsyntaxhighlight XPL0lang="xpl0">if Problem then exit 1;
</syntaxhighlight>
</lang>
 
 
Line 1,766 ⟶ 1,898:
This mostly depends on the hardware, but typically home computers would boot in BASIC and <code>CALL</code> the starting address on the disk. This means that the return address for BASIC is on top of the stack, and an <code>RET</code> will exit the program and return to BASIC, provided that execution is not inside one of the disk's subroutines. The example below is typical of a home computer such as the Amstrad CPC:
 
<langsyntaxhighlight lang="z80">;assumes this runs inline
org &1000 ;program start
main:
Line 1,772 ⟶ 1,904:
cp 'Y' ;compare to ascii capital Y
ret z ;return to BASIC if equal
jp main ;loop back to main</langsyntaxhighlight>
 
===Game Boy===
The Game Boy doesn't have BASIC to return to, and the <code>HALT</code> and <code>STOP</code> commands are a bit buggy. The easiest way to programmatically terminate the program is to trap the program counter, although it should be warned that doing so will drain the batteries more quickly than you may like.
 
<langsyntaxhighlight lang="z80">forever:
jr forever</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">if (die) System.exit();
if (die) System.exit(1);
if (die) System.exit("dumping core");</langsyntaxhighlight>
The parameter to exit (string or number) determines how hard zkl exits. 0 runs the garbage collector to close any orphaned open files, etc. Any other number doesn't. Text will cause a core dump (if $zklDumpCore is set). The OS gets to clean up any mess.
9,476

edits