Program termination: Difference between revisions

Content added Content deleted
(uBasic/4tH version added)
m (syntax highlighting fixup automation)
Line 13: Line 13:
<br><br>
<br><br>
=={{header|11l}}==
=={{header|11l}}==
<lang 11l>I problem
<syntaxhighlight lang="11l">I problem
exit(1)</lang>
exit(1)</syntaxhighlight>
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
===Commodore 64, etc.===
===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.
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.
<lang 6502>;assuming this is not a subroutine and runs inline.
<syntaxhighlight 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
cmp TestValue ;a label for a memory address that contains some value we want to test the accumulator against
beq continue
beq continue
rts ;unlike the Z80 there is no conditional return so we have to branch around the return instruction.
rts ;unlike the Z80 there is no conditional return so we have to branch around the return instruction.
continue:</lang>
continue:</syntaxhighlight>


===Nintendo Entertainment System===
===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:
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:


<lang 6502asm>sei ;disable IRQs
<syntaxhighlight lang="6502asm">sei ;disable IRQs
halt:
halt:
jmp halt ;trap the program counter</lang>
jmp halt ;trap the program counter</syntaxhighlight>


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.
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: Line 37:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program ending64.s */
/* program ending64.s */
Line 73: Line 73:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
DO
DO
IF Rand(0)=10 THEN
IF Rand(0)=10 THEN
Line 84: Line 84:
OD
OD
PrintE("This is a dead code")
PrintE("This is a dead code")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Program_termination.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Program_termination.png Screenshot from Atari 8-bit computer]
Line 100: 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.
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.
<lang ada>with Ada.Task_Identification; use Ada.Task_Identification;
<syntaxhighlight lang="ada">with Ada.Task_Identification; use Ada.Task_Identification;


procedure Main is
procedure Main is
Line 109: Line 109:
Abort_Task (Current_Task);
Abort_Task (Current_Task);
end if;
end if;
end Main;</lang>
end Main;</syntaxhighlight>
Aborting a task with Abort_Task is equivalent to ''abort'' statement,
Aborting a task with Abort_Task is equivalent to ''abort'' statement,
which is not used here because the environment task object is anonymous.
which is not used here because the environment task object is anonymous.
Line 127: Line 127:


With the first approach:
With the first approach:
<lang ada>procedure Main is
<syntaxhighlight lang="ada">procedure Main is
-- Create as many task objects as your program needs
-- Create as many task objects as your program needs
begin
begin
Line 137: Line 137:
return; -- actually, this is not needed
return; -- actually, this is not needed
end if;
end if;
end Main;</lang>
end Main;</syntaxhighlight>
A task might look like:
A task might look like:
<lang ada>task body Some_Task is
<syntaxhighlight lang="ada">task body Some_Task is
begin
begin
loop
loop
Line 152: Line 152:
end select
end select
end loop;
end loop;
end Some_Task;</lang>
end Some_Task;</syntaxhighlight>
With the second approach one simply returns from Main and all tasks are terminated by selecting the terminate alternative. Such tasks might look like:
With the second approach one simply returns from Main and all tasks are terminated by selecting the terminate alternative. Such tasks might look like:
<lang ada>task body Some_Task is
<syntaxhighlight lang="ada">task body Some_Task is
begin
begin
loop
loop
Line 163: Line 163:
end select
end select
end loop;
end loop;
end Some_Task;</lang>
end Some_Task;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
f1(integer a)
f1(integer a)
{
{
Line 180: Line 180:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
The label "stop" appears at the start of the <i>standard-postlude</i> and can be invoked to terminate any program.
The label "stop" appears at the start of the <i>standard-postlude</i> and can be invoked to terminate any program.
<lang algol68>IF problem = 1 THEN
<syntaxhighlight lang="algol68">IF problem = 1 THEN
stop
stop
FI</lang>
FI</syntaxhighlight>
The <i>standard-postlude</i> closes any opens files and basically wraps up execution.
The <i>standard-postlude</i> closes any opens files and basically wraps up execution.


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
The program can be stopped by a false assertion.
The program can be stopped by a false assertion.
<lang algolw>if anErrorOccured then assert( false );</lang>
<syntaxhighlight lang="algolw">if anErrorOccured then assert( false );</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 200: Line 200:
The memory used belongs to the application running the script and is reclaimed automatically.
The memory used belongs to the application running the script and is reclaimed automatically.


<lang applescript> if (someCondition) then error number -128</lang>
<syntaxhighlight lang="applescript"> if (someCondition) then error number -128</syntaxhighlight>


In a stay-open applet:
In a stay-open applet:


<lang applescript>on idle -- A stay-open applet's 'idle' handler is called periodically while the applet remains open.
<syntaxhighlight lang="applescript">on idle -- A stay-open applet's 'idle' handler is called periodically while the applet remains open.
-- Some code, including:
-- Some code, including:
if (someCondition) then
if (someCondition) then
Line 212: Line 212:


return 10 -- Number of seconds to the next call of this handler if the applet's still open.
return 10 -- Number of seconds to the next call of this handler if the applet's still open.
end idle</lang>
end idle</syntaxhighlight>




=={{header|APL}}==
=={{header|APL}}==
<lang apl>
<syntaxhighlight lang="apl">
#!/usr/local/bin/apl --script --
#!/usr/local/bin/apl --script --


Line 239: Line 239:


main
main
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 256: Line 256:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program ending.s */
/* program ending.s */
Line 284: Line 284:
swi 0 @ perform the system call Linux
swi 0 @ perform the system call Linux


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>problem: true
<syntaxhighlight lang="rebol">problem: true
if problem -> exit</lang>
if problem -> exit</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>If (problem)
<syntaxhighlight lang="autohotkey">If (problem)
ExitApp</lang>
ExitApp</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
Then Endif is entirely unnecessary, but it is good form.
Then Endif is entirely unnecessary, but it is good form.
<lang AutoIt>If problem Then
<syntaxhighlight lang="autoit">If problem Then
Exit
Exit
Endif</lang>
Endif</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
An "exit"-statement aborts the current script,
An "exit"-statement aborts the current script,
optionally returning a status-code:
optionally returning a status-code:
<lang awk>if(problem)exit 1</lang>
<syntaxhighlight lang="awk">if(problem)exit 1</syntaxhighlight>


Before exiting, the END-block(s) are processed. <br>
Before exiting, the END-block(s) are processed. <br>
An "exit" in an END-block causes an immediate exit:
An "exit" in an END-block causes an immediate exit:
<lang awk># usage: awk -f exittest.awk input.txt
<syntaxhighlight lang="awk"># usage: awk -f exittest.awk input.txt
BEGIN { print "# Exit-Test" }
BEGIN { print "# Exit-Test" }


Line 317: Line 317:
END { if(problem) {print "!! Problem !!"; exit 2} }
END { if(problem) {print "!! Problem !!"; exit 2} }
END { print "# Lines read:", NR }
END { print "# Lines read:", NR }
</syntaxhighlight>
</lang>
To compare, un/comment one of the lines #1 or #2:
To compare, un/comment one of the lines #1 or #2:
{{in}}
{{in}}
Line 347: Line 347:
=={{header|Axe}}==
=={{header|Axe}}==
The following example will force exit from any number of nested calls and loops:
The following example will force exit from any number of nested calls and loops:
<lang axe>Returnʳ</lang>
<syntaxhighlight lang="axe">Returnʳ</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>if problem = 1 then
<syntaxhighlight lang="qbasic">if problem = 1 then
end
end
end if</lang>
end if</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang Applesoft BASIC>10 IF 1 THEN STOP</lang>
<syntaxhighlight lang="applesoft basic">10 IF 1 THEN STOP</syntaxhighlight>


==={{header|BaCon}}===
==={{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.
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.
<lang freebasic>IF TRUE THEN END 42</lang>
<syntaxhighlight lang="freebasic">IF TRUE THEN END 42</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
Line 366: Line 366:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC> 100 IF CONDITION THEN STOP</lang>
<syntaxhighlight lang="is-basic"> 100 IF CONDITION THEN STOP</syntaxhighlight>


==={{header|Locomotive Basic}}===
==={{header|Locomotive Basic}}===
<lang locobasic>10 IF 1 THEN END</lang>
<syntaxhighlight lang="locobasic">10 IF 1 THEN END</syntaxhighlight>


==={{header|uBasic/4tH}}===
==={{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".
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".
<lang>If 1 Then Stop
<syntaxhighlight lang="text">If 1 Then Stop
If 1 Then End</lang>
If 1 Then End</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
The ZX Spectrum has a STOP command, rather than an END command:
The ZX Spectrum has a STOP command, rather than an END command:
<lang zxbasic>10 LET a = 1: LET b = 1
<syntaxhighlight lang="zxbasic">10 LET a = 1: LET b = 1
20 IF a = b THEN GO TO 9995
20 IF a = b THEN GO TO 9995
9995 STOP</lang>
9995 STOP</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>if condition exit</lang>
<syntaxhighlight lang="dos">if condition exit</syntaxhighlight>
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.
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}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> IF condition% THEN QUIT</lang>
<syntaxhighlight lang="bbcbasic"> IF condition% THEN QUIT</syntaxhighlight>
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.
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}}==
=={{header|Befunge}}==
<lang bbcbasic>_@</lang>
<syntaxhighlight lang="bbcbasic">_@</syntaxhighlight>
The @ instruction ends the program. Some interpreters revert changes to the code (made by p) while others do not.
The @ instruction ends the program. Some interpreters revert changes to the code (made by p) while others do not.


Line 399: Line 399:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
/* More "natural" way of ending the program: finish all work and return
/* More "natural" way of ending the program: finish all work and return
from main() */
from main() */
Line 416: Line 416:
of codes are agreed upon.
of codes are agreed upon.
*/
*/
}</lang>
}</syntaxhighlight>
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.
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.
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>


if(problem){
if(problem){
abort();
abort();
}</lang>
}</syntaxhighlight>
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.
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 <lang C>exit_group();</lang>
To end not just the current process, but all processes in the same group, do <syntaxhighlight lang="c">exit_group();</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>if (problem)
<syntaxhighlight lang="csharp">if (problem)
{
{
Environment.Exit(1);
Environment.Exit(1);
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
There are several ways to terminate a program. The following is mostly the same as in C:
There are several ways to terminate a program. The following is mostly the same as in C:
<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>


void problem_occured()
void problem_occured()
{
{
std::exit(EXIT_FAILURE);
std::exit(EXIT_FAILURE);
}</lang>
}</syntaxhighlight>
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.
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.
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.
<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>


void problem_occured()
void problem_occured()
{
{
std::abort();
std::abort();
}</lang>
}</syntaxhighlight>
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.
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.
<lang cpp>#include <exception>
<syntaxhighlight lang="cpp">#include <exception>


void problem_occured()
void problem_occured()
{
{
std::terminate();
std::terminate();
}</lang>
}</syntaxhighlight>
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.
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 464: Line 464:
{{trans|Java}}
{{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."
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."
<lang clojure>(if problem
<syntaxhighlight lang="clojure">(if problem
(. System exit integerErrorCode))
(. System exit integerErrorCode))
;conventionally, error code 0 is the code for "OK",
;conventionally, error code 0 is the code for "OK",
; while anything else is an actual problem
; while anything else is an actual problem
;optionally: (-> Runtime (. getRuntime) (. exit integerErrorCode))
;optionally: (-> Runtime (. getRuntime) (. exit integerErrorCode))
}</lang>
}</syntaxhighlight>
You can use <code>(-> Runtime (. getRuntime) (. addShutdownHook myThread))</code> to add threads which represent actions to be run when the program exits.
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:
This one does not perform cleanup:
<lang clojure>(if problem
<syntaxhighlight lang="clojure">(if problem
(-> Runtime (. getRuntime) (. halt integerErrorCode)))
(-> Runtime (. getRuntime) (. halt integerErrorCode)))
; conventionally, error code 0 is the code for "OK",
; conventionally, error code 0 is the code for "OK",
; while anything else is an actual problem
; while anything else is an actual problem
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{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/>
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/>
<lang cobol>IF problem
<syntaxhighlight lang="cobol">IF problem
STOP RUN
STOP RUN
END-IF</lang>
END-IF</syntaxhighlight>


<code>GOBACK</code> was added in COBOL 2002, and will terminate the program if it is reached in the '''main''' program.
<code>GOBACK</code> was added in COBOL 2002, and will terminate the program if it is reached in the '''main''' program.
<lang cobol>IF problem
<syntaxhighlight lang="cobol">IF problem
GOBACK
GOBACK
END-IF</lang>
END-IF</syntaxhighlight>


The ability to return a return code to the operating system is available for both of these statements as an extension in some compilers.
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 494: Line 494:
=={{header|Common Lisp}}==
=={{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:
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:
<lang lisp>(defun terminate (status)
<syntaxhighlight lang="lisp">(defun terminate (status)
#+sbcl ( sb-ext:quit :unix-status status) ; SBCL
#+sbcl ( sb-ext:quit :unix-status status) ; SBCL
#+ccl ( ccl:quit status) ; Clozure CL
#+ccl ( ccl:quit status) ; Clozure CL
Line 504: Line 504:
#+gcl (common-lisp-user::bye status) ; GCL
#+gcl (common-lisp-user::bye status) ; GCL
#+ecl ( ext:quit status) ; ECL
#+ecl ( ext:quit status) ; ECL
(cl-user::quit)) ; Many implementations put QUIT in the sandbox CL-USER package.</lang>
(cl-user::quit)) ; Many implementations put QUIT in the sandbox CL-USER package.</syntaxhighlight>
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.
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 514: Line 514:
=={{header|D}}==
=={{header|D}}==
The usual C functions are available, plus assert Errors and user defined Errors, and Exceptions.
The usual C functions are available, plus assert Errors and user defined Errors, and Exceptions.
<lang d>import core.stdc.stdio, core.stdc.stdlib;
<syntaxhighlight lang="d">import core.stdc.stdio, core.stdc.stdlib;


extern(C) void foo() nothrow {
extern(C) void foo() nothrow {
Line 566: Line 566:
//abort(); // Also this is allowed. Will not call foo, bar, spam.
//abort(); // Also this is allowed. Will not call foo, bar, spam.
exit(0);
exit(0);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>spam at exit
<pre>spam at exit
Line 575: Line 575:


=== Simple exit with D Runtime cleanup ===
=== Simple exit with D Runtime cleanup ===
<lang d>import core.runtime, std.c.stdlib;
<syntaxhighlight lang="d">import core.runtime, std.c.stdlib;


static ~this() {
static ~this() {
Line 595: Line 595:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Called on dexit
<pre>Called on dexit
Line 601: Line 601:


=={{header|DBL}}==
=={{header|DBL}}==
<lang DBL>IF (CONDITION) STOP</lang>
<syntaxhighlight lang="dbl">IF (CONDITION) STOP</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>System.Halt;</lang>
<syntaxhighlight lang="delphi">System.Halt;</syntaxhighlight>
or
or
<lang Delphi>System.Halt(1); // Optional exit code</lang>
<syntaxhighlight lang="delphi">System.Halt(1); // Optional exit code</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Exit indicating successful completion:
Exit indicating successful completion:
<lang e>if (true) {
<syntaxhighlight lang="e">if (true) {
interp.exitAtTop()
interp.exitAtTop()
}</lang>
}</syntaxhighlight>
Exit indicating some problem:
Exit indicating some problem:
<lang e>if (true) {
<syntaxhighlight lang="e">if (true) {
interp.exitAtTop("because the task said so")
interp.exitAtTop("because the task said so")
}</lang>
}</syntaxhighlight>
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.]
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 623: Line 623:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>if rcode != :ok, do: System.halt(1)</lang>
<syntaxhighlight lang="elixir">if rcode != :ok, do: System.halt(1)</syntaxhighlight>
<lang elixir>exit(:normal)
<syntaxhighlight lang="elixir">exit(:normal)
# or
# or
exit(:shutdown)</lang>
exit(:shutdown)</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(when something
<syntaxhighlight lang="lisp">(when something
(kill-emacs))</lang>
(kill-emacs))</syntaxhighlight>


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.
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.
Line 636: Line 636:
=={{header|Erlang}}==
=={{header|Erlang}}==
;Polite:
;Polite:
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
if problem ->
if problem ->
exit(1).</lang>
exit(1).</syntaxhighlight>


;As soon as possible:
;As soon as possible:
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
if problem ->
if problem ->
halt().</lang>
halt().</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


if condition then
if condition then
Environment.Exit 1</lang>
Environment.Exit 1</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: kernel system ;
<syntaxhighlight lang="factor">USING: kernel system ;


t [ 0 exit ] when</lang>
t [ 0 exit ] when</syntaxhighlight>
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.
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:
You can add your own shutdown hooks like so:


<lang factor>USING: init io ;
<syntaxhighlight lang="factor">USING: init io ;


[ "Exiting Factor..." print flush ] "message" add-shutdown-hook</lang>
[ "Exiting Factor..." print flush ] "message" add-shutdown-hook</syntaxhighlight>


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.
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 668: Line 668:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>debug @
<syntaxhighlight lang="forth">debug @
if QUIT \ quit back to the interpreter
if QUIT \ quit back to the interpreter
else BYE \ exit forth environment completely (e.g. end of a Forth shell script)
else BYE \ exit forth environment completely (e.g. end of a Forth shell script)
then</lang>
then</syntaxhighlight>


=={{header|Fortran}}==
=={{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.
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.
<lang fortran>IF (condition) STOP [message]
<syntaxhighlight lang="fortran">IF (condition) STOP [message]
! message is optional and is a character string.
! message is optional and is a character string.
! If present, the message is output to the standard output device.</lang>
! If present, the message is output to the standard output device.</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Line 688: Line 688:


Here is a very simple example of the use of the 'End' statement:
Here is a very simple example of the use of the 'End' statement:
<lang freebasic>'FB 1.05.0 Win64 'endprog.bas'
<syntaxhighlight lang="freebasic">'FB 1.05.0 Win64 'endprog.bas'


Dim isError As Boolean = True
Dim isError As Boolean = True
Line 698: Line 698:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


After running the program, the Windows console will look something like this:
After running the program, the Windows console will look something like this:
Line 711: Line 711:
=={{header|Gambas}}==
=={{header|Gambas}}==
In a GUI environment
In a GUI environment
<lang gambas>Public Sub Form_Open()
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim siCount As Short
Dim siCount As Short


Line 721: Line 721:
Me.Close
Me.Close


End</lang>
End</syntaxhighlight>


In a CLI environment
In a CLI environment
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
Dim siCount As Short


Line 734: Line 734:
Quit
Quit


End</lang>
End</syntaxhighlight>


=={{header|Gema}}==
=={{header|Gema}}==
Terminate with an error message and a non-zero status code if "Star Trek" is found in the input stream.
Terminate with an error message and a non-zero status code if "Star Trek" is found in the input stream.
<lang gema>Star Trek=@err{found a Star Trek reference\n}@abort</lang>
<syntaxhighlight lang="gema">Star Trek=@err{found a Star Trek reference\n}@abort</syntaxhighlight>


=={{header|Gnuplot}}==
=={{header|Gnuplot}}==
<lang Gnuplot>problem=1
<syntaxhighlight lang="gnuplot">problem=1
if (problem) {
if (problem) {
exit gnuplot
exit gnuplot
}</lang>
}</syntaxhighlight>


The Gnuplot manual under "exit" notes that "any open output files may not be completed cleanly". (Does that mean output buffers not flushed?)
The Gnuplot manual under "exit" notes that "any open output files may not be completed cleanly". (Does that mean output buffers not flushed?)
Line 753: Line 753:
===Return statement===
===Return statement===
Basically, a return statement executed from anywhere in main() terminates the program.
Basically, a return statement executed from anywhere in main() terminates the program.
<lang go>func main() {
<syntaxhighlight lang="go">func main() {
if problem {
if problem {
return
return
}
}
}</lang>
}</syntaxhighlight>
Deferred functions are run when the enclosing function returns, so in the example below, function <tt>paperwork</tt> is run.
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.
This is the idiomatic mechanism for doing any kind of necessary cleanup.
Line 767: Line 767:


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.
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 812: Line 812:
func cleanup(rec *requiresExternalCleanup) {
func cleanup(rec *requiresExternalCleanup) {
fmt.Println(rec.id, "cleanup")
fmt.Println(rec.id, "cleanup")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 832: Line 832:
===Os.Exit===
===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.
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.
<lang go>func main() {
<syntaxhighlight lang="go">func main() {
fmt.Println("main program start")
fmt.Println("main program start")


Line 844: Line 844:
os.Exit(-1)
os.Exit(-1)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 859: Line 859:
It does this only in the goroutine where panic was called.
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.
Deferred functions in other goroutines are not run and if panicking goes unrecovered and the program terminates, all other goroutines are terminated abruptly.
<lang go>func pcj() {
<syntaxhighlight lang="go">func pcj() {
fmt.Println("at the junction")
fmt.Println("at the junction")
defer func() {
defer func() {
Line 875: Line 875:
time.Sleep(1e9)
time.Sleep(1e9)
fmt.Println("main program done")
fmt.Println("main program done")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 889: Line 889:


Solution #1:
Solution #1:
<lang groovy>if (problem) System.exit(intExitCode)</lang>
<syntaxhighlight lang="groovy">if (problem) System.exit(intExitCode)</syntaxhighlight>


Solution #1:
Solution #1:
<lang groovy>if (problem) Runtime.runtime.halt(intExitCode)</lang>
<syntaxhighlight lang="groovy">if (problem) Runtime.runtime.halt(intExitCode)</syntaxhighlight>


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 IF 1 THEN STOP</lang>
<syntaxhighlight lang="qbasic">10 IF 1 THEN STOP</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad
<syntaxhighlight lang="haskell">import Control.Monad
import System.Exit
import System.Exit


Line 905: Line 905:
exitWith (ExitFailure integerErrorCode) -- some failure with code
exitWith (ExitFailure integerErrorCode) -- some failure with code
exitSuccess -- success; in GHC 6.10+
exitSuccess -- success; in GHC 6.10+
exitFailure -- generic failure</lang>
exitFailure -- generic failure</syntaxhighlight>
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.
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}}==
=={{header|HicEst}}==
<lang HicEst>ALARM( 999 )</lang>
<syntaxhighlight lang="hicest">ALARM( 999 )</syntaxhighlight>
This closes windows, dialogs, files, DLLs, and frees allocated memory. Script editing is resumed on next start.
This closes windows, dialogs, files, DLLs, and frees allocated memory. Script editing is resumed on next start.


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>exit(i) # terminates the program setting an exit code of i
<syntaxhighlight lang="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
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'</lang>
runerr(i,x) # terminates the program with run time error 'i' for value 'x'</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 921: Line 921:


Tacit version:
Tacit version:
<lang j>2!:55^:] condition</lang>
<syntaxhighlight lang="j">2!:55^:] condition</syntaxhighlight>
Explicit version:
Explicit version:
<lang j>3 : 'if. 0~: condition do. 2!:55 condition end.'</lang>
<syntaxhighlight lang="j">3 : 'if. 0~: condition do. 2!:55 condition end.'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
The call <tt>System.exit</tt> does not finalize any objects by default.
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."
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."
<lang java>if(problem){
<syntaxhighlight lang="java">if(problem){
System.exit(integerErrorCode);
System.exit(integerErrorCode);
//conventionally, error code 0 is the code for "OK",
//conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
// while anything else is an actual problem
//optionally: Runtime.getRuntime().exit(integerErrorCode);
//optionally: Runtime.getRuntime().exit(integerErrorCode);
}</lang>
}</syntaxhighlight>
You can use <code>Runtime.getRuntime().addShutdownHook(myThread);</code> to add threads which represent actions to be run when the program exits.
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:
This one does not perform cleanup:
<lang java>if(problem){
<syntaxhighlight lang="java">if(problem){
Runtime.getRuntime().halt(integerErrorCode);
Runtime.getRuntime().halt(integerErrorCode);
//conventionally, error code 0 is the code for "OK",
//conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
// while anything else is an actual problem
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|SpiderMonkey}}
{{works with|SpiderMonkey}}
The <code>quit()</code> function exits the shell.
The <code>quit()</code> function exits the shell.
<lang javascript>if (some_condition)
<syntaxhighlight lang="javascript">if (some_condition)
quit();</lang>
quit();</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 953: Line 953:


'''Example:'''
'''Example:'''
<lang sh>$ jq -n '"Hello", if 1 then error else 2 end'
<syntaxhighlight lang="sh">$ jq -n '"Hello", if 1 then error else 2 end'
"Hello"</lang>
"Hello"</syntaxhighlight>


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:
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:
<lang sh>$ jq -n '"Hello" | if 1 then error else 2 end'
<syntaxhighlight lang="sh">$ jq -n '"Hello" | if 1 then error else 2 end'
jq: error: Hello</lang>
jq: error: Hello</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
Line 969: Line 969:
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.
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.


<lang javascript>assert(0 == 1);
<syntaxhighlight lang="javascript">assert(0 == 1);


if (problem) exit(1);</lang>
if (problem) exit(1);</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
quit() # terminates program normally, with its child processes. See also exit(0).
quit() # terminates program normally, with its child processes. See also exit(0).
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 985: Line 985:
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.
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.


<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 991: Line 991:
if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem
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
println("Program terminating normally") // this line will not be executed
}</lang>
}</syntaxhighlight>
After the program has terminated, the exit status can be queried from the command line (Windows 10) as follows:
After the program has terminated, the exit status can be queried from the command line (Windows 10) as follows:
{{out}}
{{out}}
Line 1,001: Line 1,001:
=={{header|Lasso}}==
=={{header|Lasso}}==
Lasso will stop processing when it encounters an "abort". By providing a "handle" block, possible cleanups can be executed before finishing execution.
Lasso will stop processing when it encounters an "abort". By providing a "handle" block, possible cleanups can be executed before finishing execution.
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9
//[
//[


Line 1,012: Line 1,012:
abort
abort


stdoutnl('Ending execution')</lang>
stdoutnl('Ending execution')</syntaxhighlight>


{{out}}
{{out}}
Line 1,020: Line 1,020:


It is also possible to provide a "handle" block that will only execute if there's an error.
It is also possible to provide a "handle" block that will only execute if there's an error.
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


handle_error => {
handle_error => {
Line 1,031: Line 1,031:
0/0
0/0


stdoutnl('Ending execution')</lang>
stdoutnl('Ending execution')</syntaxhighlight>


{{out}}
{{out}}
Line 1,044: Line 1,044:


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.
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.
<lang lb>if 2 =2 then end</lang>
<syntaxhighlight lang="lb">if 2 =2 then end</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<lang logo>bye ; exits to shell
<syntaxhighlight lang="logo">bye ; exits to shell


throw "toplevel ; exits to interactive prompt
throw "toplevel ; exits to interactive prompt


pause ; escapes to interactive prompt for debugging
pause ; escapes to interactive prompt for debugging
continue ; resumes after a PAUSE</lang>
continue ; resumes after a PAUSE</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>if some_condition then
<syntaxhighlight lang="lua">if some_condition then
os.exit( number )
os.exit( number )
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,073: Line 1,073:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
For i=1 to 200
For i=1 to 200
Line 1,091: Line 1,091:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>beginning
<syntaxhighlight lang="m4">beginning
define(`problem',1)
define(`problem',1)
ifelse(problem,1,`m4exit(1)')
ifelse(problem,1,`m4exit(1)')
ending</lang>
ending</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,104: Line 1,104:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>If[problem, Abort[]];</lang>
<syntaxhighlight lang="mathematica">If[problem, Abort[]];</syntaxhighlight>
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.
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>
<pre>
Line 1,112: Line 1,112:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang matlab>if condition
<syntaxhighlight lang="matlab">if condition
return
return
end</lang>
end</syntaxhighlight>
There is no special way to stop a program. You can terminate it by calling <code>return</code>.
There is no special way to stop a program. You can terminate it by calling <code>return</code>.
<lang matlab>if condition
<syntaxhighlight lang="matlab">if condition
quit
quit
end</lang>
end</syntaxhighlight>
The <code>quit</code> function runs the MATLAB script <code>finish.m</code>, if it exists, and terminates MATLAB completely.
The <code>quit</code> function runs the MATLAB script <code>finish.m</code>, if it exists, and terminates MATLAB completely.


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* Basically, it's simply quit() */
<syntaxhighlight lang="maxima">/* Basically, it's simply quit() */


block([ans], loop, if (ans: read("Really quit ? (y, n)")) = 'y
block([ans], loop, if (ans: read("Really quit ? (y, n)")) = 'y
then quit()
then quit()
elseif ans = 'n then (print("Nice choice!"), 'done)
elseif ans = 'n then (print("Nice choice!"), 'done)
else (print("I dont' understand..."), go(loop)));</lang>
else (print("I dont' understand..."), go(loop)));</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>ИП0 x=0 04 С/П ...</lang>
<syntaxhighlight lang="text">ИП0 x=0 04 С/П ...</syntaxhighlight>


Condition of termination is ''Р0 = 0''.
Condition of termination is ''Р0 = 0''.
Line 1,136: Line 1,136:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
Nanoquery supports both an exit statement and an exit function. The following lines are identical:
Nanoquery supports both an exit statement and an exit function. The following lines are identical:
<syntaxhighlight lang="nanoquery">exit
<lang Nanoquery>exit
exit(0)</lang>
exit(0)</syntaxhighlight>
A value passed to the exit() function will be returned to the operating system after the program is halted.
A value passed to the exit() function will be returned to the operating system after the program is halted.


Line 1,143: Line 1,143:
Neko installs abnormal run down handlers, or can call the C ABI exit routine, which returns a status code to the operating system.
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
Program termination, in Neko
*/
*/
Line 1,152: Line 1,152:
if true sys_exit(return_code)
if true sys_exit(return_code)


$print("Control flow does not make it this far")</lang>
$print("Control flow does not make it this far")</syntaxhighlight>


{{out}}
{{out}}
Line 1,161: Line 1,161:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.Environment
<syntaxhighlight lang="nemerle">using System.Environment
...
...
when (problem) Exit(1)
when (problem) Exit(1)
...</lang>
...</syntaxhighlight>


=={{header|NetRexx}}==
=={{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.)
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.)
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,177: Line 1,177:


return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>if problem1:
<syntaxhighlight lang="nim">if problem1:
quit QuitFailure
quit QuitFailure


if problem2:
if problem2:
quit "There is a problem", QuitFailure</lang>
quit "There is a problem", QuitFailure</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>
<syntaxhighlight lang="oberon2">
IF problem THEN
IF problem THEN
HALT(1)
HALT(1)
END
END
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
The code below, will terminate a program without any cleanup.
The code below, will terminate a program without any cleanup.
<lang objeck>if(problem) {
<syntaxhighlight lang="objeck">if(problem) {
Runtime->Exit(1);
Runtime->Exit(1);
};</lang>
};</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>if problem then
<syntaxhighlight lang="ocaml">if problem then
exit integerErrorCode;
exit integerErrorCode;
(* conventionally, error code 0 is the code for "OK",
(* conventionally, error code 0 is the code for "OK",
while anything else is an actual problem *)</lang>
while anything else is an actual problem *)</syntaxhighlight>
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.
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,210: Line 1,210:
OS.exit returns to OS with return value as parameter.
OS.exit returns to OS with return value as parameter.


<lang Oforth>import: os
<syntaxhighlight lang="oforth">import: os


some_condition ifTrue: [ 0 OS.exit ]</lang>
some_condition ifTrue: [ 0 OS.exit ]</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(shutdown 0) ; it can be any exit code instead of provided 0
(shutdown 0) ; it can be any exit code instead of provided 0
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>if Problem then {Application.exit 0} end</lang>
<syntaxhighlight lang="oz">if Problem then {Application.exit 0} end</syntaxhighlight>
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>.
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}}==
=={{header|PARI/GP}}==
<lang parigp>if(stuff, quit)</lang>
<syntaxhighlight lang="parigp">if(stuff, quit)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,230: Line 1,230:
Extended Pascal (ISO standard 10206) defines a (parameter-less) <tt>procedure</tt> <tt>halt</tt>.
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]]).
UCSD Pascal’s <tt>halt</tt> takes one <tt>integer</tt> argument (cf.&nbsp;[[#Delphi|Delphi]]).
<lang pascal>if true then
<syntaxhighlight lang="pascal">if true then
begin
begin
halt
halt
end</lang>All regular cleanup procedures apply, nothing special.
end</syntaxhighlight>All regular cleanup procedures apply, nothing special.


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>if ($problem) {
<syntaxhighlight lang="perl">if ($problem) {
exit integerErrorCode;
exit integerErrorCode;
# conventionally, error code 0 is the code for "OK"
# conventionally, error code 0 is the code for "OK"
# (you can also omit the argument in this case)
# (you can also omit the argument in this case)
# while anything else is an actual problem
# while anything else is an actual problem
}</lang>
}</syntaxhighlight>


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.
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,253: Line 1,253:
=={{header|Phix}}==
=={{header|Phix}}==
To terminate the entire application:
To terminate the entire application:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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: #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;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">abort</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
To terminate just the current thread (no threads under pwa/p2js though):
To terminate just the current thread (no threads under pwa/p2js though):
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<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: #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: #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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Files will be closed automatically and memory will be freed, however any other cleanup should be invoked manually.<br>
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().
Most of my code has Abort() routines acting as wrappers for final-housekeeping-then-abort().


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>if 1 quit endif</lang>
<syntaxhighlight lang="phixmonti">if 1 quit endif</syntaxhighlight>
See Phix commments.
See Phix commments.


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>if (problem)
<syntaxhighlight lang="php">if (problem)
exit(1);</lang>
exit(1);</syntaxhighlight>
The <code>register_shutdown_function()</code> function can be used to register functions to be run when the program exits.
The <code>register_shutdown_function()</code> function can be used to register functions to be run when the program exits.


=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight lang="picat">
<lang Picat>
% ...
% ...
if problem then
if problem then
Line 1,283: Line 1,283:
end,
end,
% ...
% ...
</syntaxhighlight>
</lang>


or
or
<syntaxhighlight lang="picat">
<lang Picat>
% ...
% ...
if problem then
if problem then
Line 1,292: Line 1,292:
end,
end,
% ...
% ...
</syntaxhighlight>
</lang>




Line 1,299: Line 1,299:


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.
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.
<lang PicoLisp>(push '*Bye '(prinl "Goodbye world!"))
<syntaxhighlight lang="picolisp">(push '*Bye '(prinl "Goodbye world!"))
(bye)</lang>
(bye)</syntaxhighlight>
{{out}}
{{out}}
<pre>Goodbye world!
<pre>Goodbye world!
Line 1,306: Line 1,306:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>STOP; /* terminates the entire program */
<syntaxhighlight lang="pli">STOP; /* terminates the entire program */
/* PL/I does any required cleanup, such as closing files. */</lang>
/* PL/I does any required cleanup, such as closing files. */</syntaxhighlight>
<lang pli>STOP THREAD (tiger); /* terminates only thread "tiger". */</lang>
<syntaxhighlight lang="pli">STOP THREAD (tiger); /* terminates only thread "tiger". */</syntaxhighlight>
<lang pli>SIGNAL FINISH; /* terminates the entire program. */
<syntaxhighlight lang="pli">SIGNAL FINISH; /* terminates the entire program. */
/* PL/I does any required cleanup, */
/* PL/I does any required cleanup, */
/* such as closing files. */</lang>
/* such as closing files. */</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>if condition then
<syntaxhighlight lang="pop11">if condition then
sysexit();
sysexit();
endif;</lang>
endif;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
There are two ways which differ slightly:
There are two ways which differ slightly:
<lang postscript>condition {stop} if</lang>
<syntaxhighlight lang="postscript">condition {stop} if</syntaxhighlight>
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>
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.
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.
<lang postscript>condition {quit} if</lang>
<syntaxhighlight lang="postscript">condition {quit} if</syntaxhighlight>
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.
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}}==
=={{header|PowerShell}}==
<lang powershell>if (somecondition) {
<syntaxhighlight lang="powershell">if (somecondition) {
exit
exit
}</lang>
}</syntaxhighlight>
This ends the scope for any non-global variables defined in the script. No special cleanup is performed.
This ends the scope for any non-global variables defined in the script. No special cleanup is performed.


=={{header|Prolog}}==
=={{header|Prolog}}==
Terminate Prolog execution. Open files are closed. Exits the Interpreter.
Terminate Prolog execution. Open files are closed. Exits the Interpreter.
<lang prolog>halt.</lang>
<syntaxhighlight lang="prolog">halt.</syntaxhighlight>
Terminate Prolog execution but don't exit the Interpreter.
Terminate Prolog execution but don't exit the Interpreter.
<lang prolog>abort.</lang>
<syntaxhighlight lang="prolog">abort.</syntaxhighlight>


=={{header|PureBasic}}==
=={{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.
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.
<lang PureBasic>If problem = 1
<syntaxhighlight lang="purebasic">If problem = 1
End
End
EndIf</lang>
EndIf</syntaxhighlight>
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.
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}}==
=={{header|Python}}==
;Polite:
;Polite:
<lang python>import sys
<syntaxhighlight lang="python">import sys
if problem:
if problem:
sys.exit(1)</lang>
sys.exit(1)</syntaxhighlight>
The [http://docs.python.org/library/atexit.html atexit] module allows you to register functions to be run when the program exits.
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:
;As soon as possible:
(Signals the underlying OS to abort the program. No cleanup is performed)
(Signals the underlying OS to abort the program. No cleanup is performed)
<lang python>import os
<syntaxhighlight lang="python">import os
if problem:
if problem:
os.abort()</lang>
os.abort()</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
Line 1,364: Line 1,364:
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>
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>
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>
<lang qbasic>INPUT "Press any key...", a$
<syntaxhighlight lang="qbasic">INPUT "Press any key...", a$
IF 1 THEN SYSTEM</lang>
IF 1 THEN SYSTEM</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang r>if(problem) q(status=10)</lang>
<syntaxhighlight lang="r">if(problem) q(status=10)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,375: Line 1,375:
process, possibly returning a status code.
process, possibly returning a status code.


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(run-stuff)
(run-stuff)
(when (something-bad-happened) (exit 1))
(when (something-bad-happened) (exit 1))
</syntaxhighlight>
</lang>


In addition, Racket has "custodians", which are objects that are used to
In addition, Racket has "custodians", which are objects that are used to
Line 1,389: Line 1,389:
its client interaction is done. For example:
its client interaction is done. For example:


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(parameterize ([current-custodian (make-custodian)])
(parameterize ([current-custodian (make-custodian)])
Line 1,398: Line 1,398:
;; like file ports, network connections, etc
;; like file ports, network connections, etc
(custodian-shutdown-all (current-custodian)))
(custodian-shutdown-all (current-custodian)))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>if $problem { exit $error-code }</lang>
<syntaxhighlight lang="raku" line>if $problem { exit $error-code }</syntaxhighlight>
An <tt>exit</tt> runs all appropriate scope-leaving blocks such as <tt>LEAVE</tt>, <tt>KEEP</tt>, or <tt>UNDO</tt>,
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
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,409: Line 1,409:
=={{header|REBOL}}==
=={{header|REBOL}}==
The '''quit''' word stops all evaluation, releases operating system resources and exits the interpreter.
The '''quit''' word stops all evaluation, releases operating system resources and exits the interpreter.
<lang REBOL>if error? try [6 / 0] [quit]</lang>
<syntaxhighlight lang="rebol">if error? try [6 / 0] [quit]</syntaxhighlight>
A return value can be provided to the operating system:
A return value can be provided to the operating system:
<lang REBOL>if error? try [dangerous-operation] [quit/return -12]</lang>
<syntaxhighlight lang="rebol">if error? try [dangerous-operation] [quit/return -12]</syntaxhighlight>
Because of REBOL's tightly integrated REPL, you can also use '''q''' to do the same thing.
Because of REBOL's tightly integrated REPL, you can also use '''q''' to do the same thing.
<lang REBOL>if error? try [something-silly] [q/return -12]</lang>
<syntaxhighlight lang="rebol">if error? try [something-silly] [q/return -12]</syntaxhighlight>
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.
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.
<lang REBOL>view layout [button "stopme" [halt]]</lang>
<syntaxhighlight lang="rebol">view layout [button "stopme" [halt]]</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>problem? [ bye ] if</lang>
<syntaxhighlight lang="retro">problem? [ bye ] if</syntaxhighlight>


=={{header|REXX}}==
=={{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).
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).
<lang rexx>/*REXX program showing five ways to perform a REXX program termination. */
<syntaxhighlight lang="rexx">/*REXX program showing five ways to perform a REXX program termination. */


/*─────1st way────────────────────────────────────────────────────────*/
/*─────1st way────────────────────────────────────────────────────────*/
Line 1,450: Line 1,450:
/* │ */ /*terminated. */
/* │ */ /*terminated. */
/* ↓ */
/* ↓ */
/* e-o-f */ /* e-o-f = end-of-file. */</lang>
/* e-o-f */ /* e-o-f = end-of-file. */</syntaxhighlight>


Regina actually implies a RETURN when the end of the program is found at the end of a subroutine:
Regina actually implies a RETURN when the end of the program is found at the end of a subroutine:
<lang rexx>Parse Version v
<syntaxhighlight lang="rexx">Parse Version v
Say v
Say v
Call sub
Call sub
Say 'Back from sub'
Say 'Back from sub'
Exit
Exit
sub:</lang>
sub:</syntaxhighlight>
{{out}}
{{out}}
<pre>REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015
<pre>REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015
Line 1,464: Line 1,464:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
for n = 1 to 10
for n = 1 to 10
see n + nl
see n + nl
if n = 5 exit ok
if n = 5 exit ok
next
next
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>if problem
<syntaxhighlight lang="ruby">if problem
exit(1)
exit(1)
end
end
Line 1,479: Line 1,479:
if problem
if problem
abort # equivalent to exit(1)
abort # equivalent to exit(1)
end</lang>
end</syntaxhighlight>


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.
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.


<lang ruby>if problem
<syntaxhighlight lang="ruby">if problem
exit! # default value 1
exit! # default value 1
end</lang>
end</syntaxhighlight>
Exits the process immediately. No exit handlers are run.
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.
<code>exit!</code> is different from <code>exit</code> and it doesn't do an exception handling.


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>if whatever then end</lang>
<syntaxhighlight lang="runbasic">if whatever then end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
===Return statement===
===Return statement===
A return statement executed in the main() function will exit the program.
A return statement executed in the main() function will exit the program.
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
println!("The program is running");
println!("The program is running");
return;
return;
println!("This line won't be printed");
println!("This line won't be printed");
}</lang>
}</syntaxhighlight>


===Exit function===
===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.
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.


<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
if problem {
if problem {
std::process::exit(1); // 1 is the exit code
std::process::exit(1); // 1 is the exit code
}
}
}</lang>
}</syntaxhighlight>


===Panics===
===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.
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.


<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
println!("The program is running");
println!("The program is running");
panic!("A runtime panic occured");
panic!("A runtime panic occured");
println!("This line won't be printed");
println!("This line won't be printed");
}</lang>
}</syntaxhighlight>
Because of the panic, the last line will not run. If the panic happened in another thread, the program could keep running.
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'''
'''Panic Inside a Thread'''
<lang rust>use std::thread;
<syntaxhighlight lang="rust">use std::thread;


fn main() {
fn main() {
Line 1,532: Line 1,532:


println!("This line should be printed");
println!("This line should be printed");
}</lang>
}</syntaxhighlight>
Now the panic will be contained inside the background thread and will not affect the rest of the program.
Now the panic will be contained inside the background thread and will not affect the rest of the program.


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang Scala>if (problem) {
<syntaxhighlight lang="scala">if (problem) {
// sys.exit returns type "Nothing"
// sys.exit returns type "Nothing"
sys.exit(0)
sys.exit(0)
Line 1,543: Line 1,543:
// while anything else is an actual problem
// while anything else is an actual problem
}
}
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Scheme|R<sup>6</sup>RS}}
{{works with|Scheme|R<sup>6</sup>RS}}
<lang scheme>(if problem
<syntaxhighlight lang="scheme">(if problem
(exit)) ; exit successfully</lang>
(exit)) ; exit successfully</syntaxhighlight>
or
or
<lang scheme>(if problem
<syntaxhighlight lang="scheme">(if problem
(exit #f)) ; exit unsuccessfully</lang>
(exit #f)) ; exit unsuccessfully</syntaxhighlight>
or
or
<lang scheme>(if problem
<syntaxhighlight lang="scheme">(if problem
(exit some-value)) ; converts "some-value" into an appropriate exit code for your system</lang>
(exit some-value)) ; converts "some-value" into an appropriate exit code for your system</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
When a program is stopped with exit(PROGRAM) allocated memory is freed and open files are closed,
When a program is stopped with exit(PROGRAM) allocated memory is freed and open files are closed,
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 1,566: Line 1,566:
exit(PROGRAM);
exit(PROGRAM);
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
The '''exit all''' command halts execution. Open files, sockets, database connections, etc. are closed and allocated memory is freed.
The '''exit all''' command halts execution. Open files, sockets, database connections, etc. are closed and allocated memory is freed.
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
if problemCondition then exit all
if problemCondition then exit all
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>if (problem) {
<syntaxhighlight lang="ruby">if (problem) {
Sys.exit(code);
Sys.exit(code);
}</lang>
}</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang Simula>IF terminallyIll THEN terminate_program;</lang>»The procedure "terminate_program" terminates program execution. It&nbsp;closes SYSIN&nbsp;and&nbsp;SYSOUT.
<syntaxhighlight lang="simula">IF terminallyIll THEN terminate_program;</syntaxhighlight>»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]]
&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}}==
=={{header|Slate}}==
<lang slate>problem ifTrue: [exit: 1].</lang>
<syntaxhighlight lang="slate">problem ifTrue: [exit: 1].</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 1,593: Line 1,593:
as the exit status of the program,
as the exit status of the program,
and the :s( ) goto transfers control to END.
and the :s( ) goto transfers control to END.
<lang SNOBOL4> &code = condition errlevel :s(end)</lang>
<syntaxhighlight lang="snobol4"> &code = condition errlevel :s(end)</syntaxhighlight>


=={{header|SSEM}}==
=={{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.
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.
<lang ssem>00000000000000110000000000000000 Test
<syntaxhighlight lang="ssem">00000000000000110000000000000000 Test
00000000000001110000000000000000 Stop</lang>
00000000000001110000000000000000 Stop</syntaxhighlight>
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.
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}}==
=={{header|Standard ML}}==
No cleanup is performed.
No cleanup is performed.
<lang sml>if problem then
<syntaxhighlight lang="sml">if problem then
OS.Process.exit OS.Process.failure
OS.Process.exit OS.Process.failure
(* valid status codes include OS.Process.success and OS.Process.failure *)
(* valid status codes include OS.Process.success and OS.Process.failure *)
else
else
()</lang>
()</syntaxhighlight>
The <code>OS.Process.atExit</code> function can be used
The <code>OS.Process.atExit</code> function can be used
to register functions to be run when the program exits.
to register functions to be run when the program exits.
Line 1,617: Line 1,617:
At the script level, all that is needed to make the program terminate
At the script level, all that is needed to make the program terminate
is the <tt>exit</tt> command:
is the <tt>exit</tt> command:
<lang tcl>if {$problem} {
<syntaxhighlight lang="tcl">if {$problem} {
# Print a “friendly” message...
# Print a “friendly” message...
puts stderr "some problem occurred"
puts stderr "some problem occurred"
# Indicate to the caller of the program that there was a problem
# Indicate to the caller of the program that there was a problem
exit 1
exit 1
}</lang>
}</syntaxhighlight>
Alternatively, in a top-level script but ''not'' an event handler:
Alternatively, in a top-level script but ''not'' an event handler:
<lang tcl>if {$problem} {
<syntaxhighlight lang="tcl">if {$problem} {
error "some problem occurred"
error "some problem occurred"
}</lang>
}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 1,636: Line 1,636:


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
<lang ti89b>Prgm
<syntaxhighlight lang="ti89b">Prgm
...
...
Stop
Stop
...
...
EndPrgm</lang>
EndPrgm</syntaxhighlight>


=={{header|Tiny BASIC}}==
=={{header|Tiny BASIC}}==
You can either halt the program directly within the conditional...
You can either halt the program directly within the conditional...
<lang tinybasic> LET I = 0
<syntaxhighlight lang="tinybasic"> LET I = 0
10 IF I = 10 THEN END
10 IF I = 10 THEN END
LET I = I + 1
LET I = I + 1
PRINT I
PRINT I
GOTO 10</lang>
GOTO 10</syntaxhighlight>


...or allow it to fall through to the end of the program.
...or allow it to fall through to the end of the program.


<lang tinybasic> LET I = 0
<syntaxhighlight lang="tinybasic"> LET I = 0
10 LET I = I + 1
10 LET I = I + 1
PRINT I
PRINT I
IF I < 10 THEN GOTO 10</lang>
IF I < 10 THEN GOTO 10</syntaxhighlight>


=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(if errorCode
(if errorCode
(exit errorCode))
(exit errorCode))
</syntaxhighlight>
</lang>


=={{header|True BASIC}}==
=={{header|True BASIC}}==
Line 1,667: Line 1,667:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
IF (condition==1) STOP
IF (condition==1) STOP
-> execution stops and message:
-> execution stops and message:
IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP "</lang>
IF (condition==2) ERROR/STOP "condition ",condition, " Execution STOP "</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh


a='1'
a='1'
Line 1,681: Line 1,681:
exit 239 # Unexpected error
exit 239 # Unexpected error
fi
fi
exit 0 # Program terminated normally</lang>
exit 0 # Program terminated normally</syntaxhighlight>


=={{header|Unlambda}}==
=={{header|Unlambda}}==
<lang unlambda>`ei</lang>
<syntaxhighlight lang="unlambda">`ei</syntaxhighlight>
Note: the argument to the <code>e</code> function is the return value of the program; however many implementation simply ignore it.
Note: the argument to the <code>e</code> function is the return value of the program; however many implementation simply ignore it.


Line 1,691: Line 1,691:
=={{header|Ursa}}==
=={{header|Ursa}}==
Standard Ursa supports the stop function, which immediately halts program execution.
Standard Ursa supports the stop function, which immediately halts program execution.
<lang ursa>stop</lang>
<syntaxhighlight lang="ursa">stop</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>'In case of problem this will terminate the program (without cleanup):
<syntaxhighlight lang="vb">'In case of problem this will terminate the program (without cleanup):
If problem then End
If problem then End
'As VBA is run within an application, such as Excel, a more rigorous way would be:
'As VBA is run within an application, such as Excel, a more rigorous way would be:
If problem then Application.Quit
If problem then Application.Quit
'This will stop the application, but will prompt you to save work.</lang>
'This will stop the application, but will prompt you to save work.</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
No matter how deep you're in, <code>wscript.quit</code> will get you out.
No matter how deep you're in, <code>wscript.quit</code> will get you out.
<lang vb>dim i, j
<syntaxhighlight lang="vb">dim i, j
j = 0
j = 0
do
do
Line 1,712: Line 1,712:
wend
wend
next
next
loop</lang>
loop</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>if (#99 == 1) { Return } // Exit current macro. Return to calling macro.
<syntaxhighlight 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 == 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 == 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 == 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 == 5) { Xall } // Exit Vedit. Save changed files without prompting.
if (#99 == 6) { Qall } // Exit Vedit. Do not save any files.</lang>
if (#99 == 6) { Qall } // Exit Vedit. Do not save any files.</syntaxhighlight>
Return or Break_Out() do not perform any cleanup. If needed, cleanup has to be done in the macro before exit.
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.
Special ''locked-in macro'' can be used to perform cleanup in case user presses Break key.
Line 1,732: Line 1,732:


When the app needs to end, for whatever reason, problem or not, it's always a good idea to unload the forms ''first''.
When the app needs to end, for whatever reason, problem or not, it's always a good idea to unload the forms ''first''.
<lang vb>Sub Main()
<syntaxhighlight lang="vb">Sub Main()
'...
'...
If problem Then
If problem Then
Line 1,741: Line 1,741:
End If
End If
'...
'...
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 1,757: Line 1,757:


The following example illustrates the use of Fiber.suspend in a Wren CLI script.
The following example illustrates the use of Fiber.suspend in a Wren CLI script.
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout


System.write("Do you want to terminate the program y/n ? ")
System.write("Do you want to terminate the program y/n ? ")
Line 1,766: Line 1,766:
Fiber.suspend() // return to OS
Fiber.suspend() // return to OS
}
}
System.print("OK, carrying on")</lang>
System.print("OK, carrying on")</syntaxhighlight>


{{out}}
{{out}}
Line 1,787: Line 1,787:
change the commands the batch file executes.
change the commands the batch file executes.


<lang XPL0>if Problem then exit 1;
<syntaxhighlight lang="xpl0">if Problem then exit 1;
</syntaxhighlight>
</lang>




Line 1,802: Line 1,802:
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:
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:


<lang z80>;assumes this runs inline
<syntaxhighlight lang="z80">;assumes this runs inline
org &1000 ;program start
org &1000 ;program start
main:
main:
Line 1,808: Line 1,808:
cp 'Y' ;compare to ascii capital Y
cp 'Y' ;compare to ascii capital Y
ret z ;return to BASIC if equal
ret z ;return to BASIC if equal
jp main ;loop back to main</lang>
jp main ;loop back to main</syntaxhighlight>


===Game Boy===
===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.
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.


<lang z80>forever:
<syntaxhighlight lang="z80">forever:
jr forever</lang>
jr forever</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>if (die) System.exit();
<syntaxhighlight lang="zkl">if (die) System.exit();
if (die) System.exit(1);
if (die) System.exit(1);
if (die) System.exit("dumping core");</lang>
if (die) System.exit("dumping core");</syntaxhighlight>
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.
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.