Exceptions: Difference between revisions

16,775 bytes added ,  1 month ago
Add page to "Flow control" category.
(Add page to "Flow control" category.)
 
(39 intermediate revisions by 21 users not shown)
Line 4:
{{omit from|M4}}
{{omit from|Retro}}
[[Category:Flow control]]
 
This task is to give an example of an exception handling routine
Line 14 ⟶ 15:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">T SillyError
String message
F (message)
Line 20 ⟶ 21:
 
X.try
X.throw SillyError(‘egg’)
X.catch SillyError se
print(se.message)</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
{{works with|MS-DOS}}
 
An exception in assembly language is often little more than just a conditional branch. Most MS-DOS system calls return the carry flag set if an error occured, and the error code will be returned in <code>AX</code>. This lets you write your own exception handler that prints a relevant error message to the screen. You'll need to read the documentation to know what each error code means.
 
<syntaxhighlight lang="asm">;syscall for creating a new file.
mov dx,offset filename
mov cx,0
mov ah,5Bh
int 21h
;if error occurs, will return carry set and error code in ax
;Error code 03h = path not found
;Error code 04h = Too many open files
;Error code 05h = Access denied
;Error code 50h = File already exists
 
jnc noError ;continue with program
 
cmp ax,03h
je PathNotFoundError ;unimplemented exception handler
 
cmp ax,04h
je TooManyOpenFilesError
 
cmp ax,05h
je AccessDeniedError
 
cmp ax,50h
je FileAlreadyExistsError
 
noError:</syntaxhighlight>
 
=={{header|Ada}}==
 
'''Define an exception'''
<syntaxhighlight lang ="ada">Foo_Error : exception;</langsyntaxhighlight>
 
'''Raise an exception'''
<langsyntaxhighlight lang="ada">procedure Foo is
begin
raise Foo_Error;
end Foo;</langsyntaxhighlight>
Re-raising once caught exception:
<langsyntaxhighlight lang="ada"> ...
exception
when Foo_Error =>
if ... then -- Alas, cannot handle it here,
raise; -- continue propagation of
end if;</langsyntaxhighlight>
 
'''Handle an exception'''
<langsyntaxhighlight lang="ada">procedure Call_Foo is
begin
Foo;
Line 51 ⟶ 84:
when others =>
... -- this catches all other exceptions
end Call_Foo;</langsyntaxhighlight>
 
'''Ada.Exceptions'''<br>
The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of:
<langsyntaxhighlight lang="ada">with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 66 ⟶ 99:
when Error : others =>
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;</langsyntaxhighlight>
 
=={{header|Aikido}}==
Line 73 ⟶ 106:
'''Catching exceptions'''<br>
There is one <code>catch</code> clause per <code>try</code> statement. The variable caught is whatever is thrown. It does not have to be a particular type, although there is a <code>System.Exception</code> class defined for system exceptions.
<langsyntaxhighlight lang="aikido">
try {
var lines = readfile ("input.txt")
Line 81 ⟶ 114:
}
 
</syntaxhighlight>
</lang>
 
'''Throwing exceptions'''<br>
You can throw any value.
<langsyntaxhighlight lang="aikido">
if (error) {
throw "Error"
Line 95 ⟶ 128:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
'''Simple Exception Throwing'''
<langsyntaxhighlight lang="aime">void
throwing(void)
{
Line 123 ⟶ 156:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>ready to catch
Line 130 ⟶ 163:
caught!</pre>
'''Exception Types'''
<langsyntaxhighlight lang="aime">void
ft(integer a, text &s)
{
Line 168 ⟶ 201:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>aime: tmp/et1: 6: bad number
Line 188 ⟶ 221:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.8 algol68g-2.8].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude/event_base(obj).a68'''<langsyntaxhighlight lang="algol68">COMMENT
Define an general event handling mechanism on MODE OBJ:
* try to parallel pythons exception handling flexibility
Line 306 ⟶ 339:
OP (SCOPEOBJ #up scope#)VOID RESET = obj reset;
 
SKIP</langsyntaxhighlight>'''File: test/event.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
 
MODE OBJ=UNION(REF INT, REF REAL, REF STRING,# etc # VOID);
Line 353 ⟶ 386:
RESET obj scope reset;
 
"finally: raise the base unmendable event" RAISE obj eventb</langsyntaxhighlight>{{out}}
<pre>
sum sqs: +4900
Line 394 ⟶ 427:
 
'''try'''
<langsyntaxhighlight lang="applescript">try
set num to 1 / 0
--do something that might throw an error
end try</langsyntaxhighlight>
 
'''try-on error'''
<langsyntaxhighlight lang="applescript">try
set num to 1 / 0
--do something that might throw an error
Line 406 ⟶ 439:
--errMess and number errNum are optional
display alert "Error # " & errNum & return & errMess
end try</langsyntaxhighlight>
 
'''error'''
<langsyntaxhighlight lang="applescript">error "Error message." number 2000</langsyntaxhighlight>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 REM TRY
110 ONERR GOTO 160"CATCH
120 PRINT 1E99
130 POKE 216,0
140 PRINT "NEVER REACHED."
150 GOTO 200"END TRY
160 REM CATCH
170 POKE 216,0
180 LET E = PEEK (222)
190 PRINT "ERROR "E" OCCURRED."
200 REM END TRY</syntaxhighlight>
{{out}}
<pre>ERROR 133 OCCURRED.
</pre>
=={{header|AutoHotkey}}==
=== True exceptions ===
Line 415 ⟶ 463:
In [[AutoHotkey_L]] [http://l.autohotkey.net/docs/commands/Try.htm Try], [http://l.autohotkey.net/docs/commands/Catch.htm Catch], and [http://l.autohotkey.net/docs/commands/Throw.htm Throw] are available to handle exceptions.<br/>
From the [http://l.autohotkey.net/docs/commands/Throw.htm Throw documentation]:
<syntaxhighlight lang="ahk">try
<lang AHK>try
BadlyCodedFunc()
catch e
Line 422 ⟶ 470:
BadlyCodedFunc() {
throw Exception("Fail", -1)
}</langsyntaxhighlight>
=== ErrorLevel-based exceptions ===
In [[AutoHotkey_Basic]], the only option for error-handling is using ErrorLevel
<syntaxhighlight lang="autohotkey">foo()
<lang AutoHotkey>foo()
If ErrorLevel
Msgbox calling foo failed with: %ErrorLevel%
Line 436 ⟶ 484:
ErrorLevel = foo_error
Return
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
<lang bbcbasic> ON ERROR PROCerror(ERR, REPORT$) : END
<syntaxhighlight lang="bbcbasic"> ON ERROR PROCerror(ERR, REPORT$) : END
ERROR 100, "User-generated exception"
Line 448 ⟶ 497:
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 457 ⟶ 506:
 
=={{header|blz}}==
<langsyntaxhighlight lang="blz">
try
1 / 0 # Throw an exception
Line 464 ⟶ 513:
print("An error occured!")
end
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
Line 488 ⟶ 537:
percolates further up, so calling the function <code>MyFunction</code> fails as well, making the whole program fail.
 
<langsyntaxhighlight lang="bracmat">( ( MyFunction
= someText XMLstuff
. ( get$!arg:?someText
Line 504 ⟶ 553:
)
& MyFunction$"Tralula.txt"
);</langsyntaxhighlight>
If you copy/paste this code to the Bracmat prompt <em>without the statement delimiter <code>;</code></em>, you will see an 'F' after the output, indicating that your input failed to
evaluate successfully.
Line 511 ⟶ 560:
F
</pre>
 
=={{header|BQN}}==
The Catch operator (<code>⎊</code>) is the main method of handling exceptions in BQN.
 
If the left function fails, the right function is executed with the given argument.
 
<syntaxhighlight lang="bqn">C←{𝕊:2‿𝕩⥊2}⎊{"Exception caught"‿𝕩}
 
•Show C 3
•Show C "dsda"</syntaxhighlight>
<syntaxhighlight lang="bqn">┌─
╵ 2 2 2
2 2 2
⟨ "Exception caught" "dsda" ⟩</syntaxhighlight>
 
=={{header|C}}==
Line 518 ⟶ 582:
'''try-catch'''
 
<langsyntaxhighlight lang="c">#include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
Line 544 ⟶ 608:
/* there is no way to "let the exception through" */
}
}</langsyntaxhighlight>
 
With multi-thread support and nested exceptions
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <setjmp.h>
Line 631 ⟶ 695:
}
 
</syntaxhighlight>
</lang>
Now all we need to do is add a finally block :) hint: it is possible
 
=={{header|C++ sharp|C#}}==
{{works with|Visual Studio|2005}}
 
C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called
if an exception is thrown.
 
The exception can be of any type, this includes int's, other primitives, as well as objects.
 
'''Defining exceptions'''
<langsyntaxhighlight cpplang="csharp">structpublic class MyException : Exception
{
// data with info about exception
};</langsyntaxhighlight>
 
There's also a class <tt>std::exception</tt> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <tt>std::runtime_error</tt> which derive from <tt>std::exception</tt>.
 
<lang cpp>#include <exception>
struct MyException: std::exception
{
char const* what() const throw() { return "description"; }
}</lang>
 
Note that in principle you can throw any copyable type as exception, including built-in types.
 
'''Throw exceptions'''
<syntaxhighlight lang="csharp">void foo()
<lang cpp>// this function can throw any type of exception
void foo()
{
throw MyException();
}</syntaxhighlight>
}
 
// this function can only throw the types of exceptions that are listed
void foo2() throw(MyException)
{
throw MyException();
}
 
// this function turns any exceptions other than MyException into std::bad_exception
void foo3() throw(MyException, std::bad_exception)
{
throw MyException();
}</lang>
 
'''Catching exceptions'''
<langsyntaxhighlight cpplang="csharp">try {
foo();
}
catch (MyException &exce)
{
// handle exceptions of type MyException and derived
}
catch
catch (std::exception &exc)
{
// handle exceptions derived from std::exception, which were not handled by above catches
// e.g.
std::cerr << exc.what() << std::endl;
}
catch (...)
{
// handle any type of exception not handled by above catches
}</langsyntaxhighlight>
 
=={{header|C sharp|C#++}}==
 
{{works with|Visual Studio|2005}}
In C++ an exception can be of any copyable type, this includes int's, other primitives, as well as objects.
 
'''Defining exceptions'''
<syntaxhighlight lang csharp="cpp">public classstruct MyException : Exception
{
// data with info about exception
};</langsyntaxhighlight>
 
However thrown exceptions should almost always derive from <tt>std::exception</tt>. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information. There are also more specific classes like <tt>std::runtime_error</tt> which also derive from <tt>std::exception</tt>.
 
<syntaxhighlight lang="cpp">#include <exception>
struct MyException: std::exception
{
virtual const char* what() const noexcept { return "description"; }
}</syntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight csharplang="cpp">void foo()
{
throw MyException();
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight csharplang="cpp">try {
foo();
}
catch (MyException e&exc)
{
// handle exceptions of type MyException and derived
}
catch (std::exception &exc)
catch
{
// handle exceptions derived from std::exception, which were not handled by above catches
// e.g.
std::cerr << exc.what() << std::endl;
}
catch (...)
{
// handle any type of exception not handled by above catches
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Expression handling in Clojure is basically like Java in S-expressions:
<langsyntaxhighlight lang="clojure">(try
(if (> (rand) 0.5)
(throw (RuntimeException. "oops!"))
Line 732 ⟶ 778:
(println e)
(finally
(println "always see this"))</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
Line 739 ⟶ 785:
inside &lt;cfscript&gt;:
 
<langsyntaxhighlight lang="cfm">try {
foo();
} catch (Any e) {
// handle exception e
}</langsyntaxhighlight>
 
otherwise:
<langsyntaxhighlight lang="cfm"><cftry>
<cfcatch type="Database|...">
</cfcatch>
</cftry></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 755 ⟶ 801:
The Common Lisp condition system allows much more control over condition signaling and condition handling than many exception-based systems. The following example, however, simply defines a condition type, <code>unexpected-odd-number</code>, defines a function <code>get-number</code> which generates a random number, returning it if it is even, but signaling an <code>unexpected-odd-number</code> condition if it is odd. The function <code>get-even-number</code> uses <code>[http://www.lispworks.com/documentation/HyperSpec/Body/m_hand_1.htm handler-case]</code> to call <code>get-number</code> returning its result if no condition is signaled, and, in the case that an <code>unexpected-odd-number</code> condition is signaled, returning one plus the odd number.
 
<langsyntaxhighlight lang="lisp">(define-condition unexpected-odd-number (error)
((number :reader number :initarg :number))
(:report (lambda (condition stream)
Line 768 ⟶ 814:
(handler-case (get-number)
(unexpected-odd-number (condition)
(1+ (number condition)))))</langsyntaxhighlight>
 
A good introduction to Lisp's condition system is the chapter [http://gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html Beyond Exception Handling: Conditions and Restarts] from Peter Seibel's [http://gigamonkeys.com/book/ Practical Common Lisp].
Line 775 ⟶ 821:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
/// Throw Exceptions
Line 809 ⟶ 855:
void main() {
test4();
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
'''Throw Exceptions'''
<langsyntaxhighlight lang="delphi">procedure test;
begin
raise Exception.Create('Sample Exception');
end;</langsyntaxhighlight>
 
'''Catch Exceptions'''
<langsyntaxhighlight lang="delphi">procedure test2;
begin
try
Line 828 ⟶ 874:
raise; // Rethrowing
end;
end;</langsyntaxhighlight>
 
'''Ways to implement finally'''
<langsyntaxhighlight lang="delphi">procedure test3;
begin
try
Line 838 ⟶ 884:
ShowMessage('test3 finally');
end;
end;</langsyntaxhighlight>
 
=={{header|Déjà VuDyalect}}==
 
<syntaxhighlight lang="dyalect">func Integer.Add(x) {
<lang dejavu>stuff-going-wrong:
throw @NegativesNotAllowed(x) when x < 0
raise :value-error
this + x
 
}
try:
stuff-going-wrong
try {
catch value-error:
12.Add(-5)
!print "Whoops!"</lang>
} catch {
{{out}}
@NegativesNotAllowed(x) => print("Negative number: \(x)")
<pre>Whoops!</pre>
}</syntaxhighlight>
 
=={{header|DWScript}}==
 
'''Throw Exceptions'''
<langsyntaxhighlight lang="delphi">procedure Test;
begin
raise Exception.Create('Sample Exception');
end;</langsyntaxhighlight>
 
'''Catch Exceptions'''
<langsyntaxhighlight lang="delphi">procedure Test2;
begin
try
Line 871 ⟶ 918:
end;
end;
end;</langsyntaxhighlight>
 
'''Ways to implement finally'''
<langsyntaxhighlight lang="delphi">procedure Test3;
begin
try
Line 881 ⟶ 928:
PrintLn('Test3 finally');
end;
end;</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
 
<syntaxhighlight lang="dejavu">stuff-going-wrong:
raise :value-error
 
try:
stuff-going-wrong
catch value-error:
!print "Whoops!"</syntaxhighlight>
{{out}}
<pre>Whoops!</pre>
 
=={{header|E}}==
Line 899 ⟶ 958:
<code>throw</code> is the built-in ''function'' which throws exceptions in the conventional sense: control goes to the <code>catch</code> block of the most recently entered <code>try</code>/<code>catch</code> construct.
 
<langsyntaxhighlight lang="e">def nameOf(arg :int) {
if (arg == 43) {
return "Bob"
Line 913 ⟶ 972:
return ["notok", exceptionObj]
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? catching(42)
# value: ["not ok", problem: Who?]
 
Line 922 ⟶ 981:
 
? catching(45.7)
# value: ["not ok", problem: the float64 45.7 doesn't coerce to an int]</langsyntaxhighlight>
 
However, there is a problem here: exceptions accidentally produced or uncaught from inside a given module can lead to the calling program getting information about the internals that it shouldn't have (possibly a security problem). As a result of this, we are planning to move to a 'sealed exception' model where throw and catch have the same control flow, but only debuggers can see any information in a ''caught'' exception other than "a throw happened". For situations where the caller ''should'' have information about what happened, the ejector mechanism will be used.
Line 934 ⟶ 993:
The above code rewritten to use ejectors:
 
<langsyntaxhighlight lang="e">def nameOf(arg :int, ejector) {
if (arg == 43) {
return "Bob"
Line 948 ⟶ 1,007:
return ["notok", exceptionObj]
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? catching(42)
# value: ["not ok", problem: Who?]
 
Line 957 ⟶ 1,016:
 
? catching(45.7)
# problem: the float64 45.7 doesn't coerce to an int</langsyntaxhighlight>
 
Note that the escape-catch block does ''not'' catch the coercion error resulting from passing a float64 instead of an int, since that is an (implicit) throw.
Line 967 ⟶ 1,026:
For example, suppose we have nameOf written as follows:
 
<langsyntaxhighlight lang="e">var nameTable := null
def nameOf(arg :int, ejector) {
if (nameTable == null) {
Line 977 ⟶ 1,036:
ejector(makeNotFoundException("Who?"))
}
}</langsyntaxhighlight>
 
Suppose that loading the parser, or reading the file, throws a NotFoundException (note this exception type was made up for this example). Even though it is of the same type as the "Who?" exception, it will not be caught by the caller's escape/catch block since it was not passed via the ejector, whereas a traditional "try { ... } catch ex :NotFoundException { ... }" as in other languages would, leading to incorrect handling of the error.
Line 984 ⟶ 1,043:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="elena">class MyException : Exception
{
constructor new()
<= super new("MyException raised");
}</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="elena">foo()
{
MyException.new().raise()
}
</syntaxhighlight>
</lang>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="elena">try
{
o.foo()
}
catch:(MyException e)
{
// handle exceptions of type MyException and derived
}</langsyntaxhighlight>
 
'''Catching any exception'''
<syntaxhighlight lang ="elena">o.foo() | on:(e) try
{
foo.fail()
}
catch(Exception e)
{
// handle any type of exception
};</langsyntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( exceptions ).
 
Line 1,027 ⟶ 1,090:
 
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,037 ⟶ 1,100:
 
'''Throw Exceptions'''
<langsyntaxhighlight lang="factor">"Install Linux, Problem Solved" throw
 
TUPLE: velociraptor ;
\ velociraptor new throw</langsyntaxhighlight>
 
Or a shorthand for this:
<langsyntaxhighlight lang="factor">ERROR: velociraptor ;
velociraptor</langsyntaxhighlight>
 
'''Catch Exceptions'''
<langsyntaxhighlight lang="factor">! Preferred exception handling
: try-foo
[ foo ] [ foo-failed ] recover ;
Line 1,058 ⟶ 1,121:
[ "Fail" throw ] catch ! returns "Fail"
[ "Hi" print ] catch ! returns f (looks the same as throwing f; don't throw f)
[ f throw ] catch ! returns f, bad! use recover or cleanup instead</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy"># define custom exception class
# StandardError is base class for all exception classes
class MyError : StandardError {
Line 1,080 ⟶ 1,143:
# this will always be executed (as in e.g. Java)
"This is how exception handling in Fancy works :)" println
}</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
// Create a new error class by subclassing sys::Err
const class SpecialErr : Err
Line 1,108 ⟶ 1,171:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,120 ⟶ 1,183:
 
'''Throw Exceptions'''
<langsyntaxhighlight lang="forth">: f ( -- ) 1 throw ." f " ; \ will throw a "1"
: g ( -- ) 0 throw ." g " ; \ does not throw</langsyntaxhighlight>
 
'''Catch Exceptions'''
<langsyntaxhighlight lang="forth">: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;
: test ( -- )
['] f catch report
['] g catch report ;</langsyntaxhighlight>
test example. (Output shown in bold)
<langsyntaxhighlight lang="forth">cr test
'''caught 1 g no throw ok'''</langsyntaxhighlight>
 
Note that CATCH only restores the stack pointers, not the stack values, so any values that were changed during the execution of the token will have undefined values. In practice, this means writing code to clean up the stack, like this:
<langsyntaxhighlight lang="forth">10 ['] myfun catch if drop then</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
FreeBASIC does not support exceptions or the Try/Catch/Finally statement, as such.
However, you can use the Err() function, together with a Switch statement, to provide somewhat similar functionality:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Enum ErrorType
Line 1,167 ⟶ 1,230:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,176 ⟶ 1,239:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c3abec93bc7f135203f1f7582f5c3a19 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iInteger As Integer
 
Line 1,205 ⟶ 1,268:
Print Error.Text
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,220 ⟶ 1,283:
<tt>recover()</tt> needs to be called in a "deferred" function call, otherwise it will have no effect. <tt>defer</tt> delays the function call until the current function returns (or fails).
 
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,241 ⟶ 1,304:
foo()
fmt.Println("glad that's over.")
}</langsyntaxhighlight>[http://play.golang.org/p/9ymYAmOMIP Run in the Go Playground].
{{out}}
<pre>
Line 1,257 ⟶ 1,320:
'''Throw exceptions'''<br>
In the context of the IO monad, use "throwIO" to throw exceptions; the expression will return any type:
<langsyntaxhighlight lang="haskell">do {- ... -}
throwIO SomeException</langsyntaxhighlight>
 
In purely functional context, use "throw" to throw exceptions; the expression will match any type:
<langsyntaxhighlight lang="haskell">if condition then 3
else throw SomeException</langsyntaxhighlight>
 
To throw a user-defined exception, use "throwDyn":
<langsyntaxhighlight lang="haskell">if condition then 3
else throwDyn myException</langsyntaxhighlight>
 
'''Catching exceptions'''<br>
The "catch" function performs the whole try-catch stuff. It is usually used in infix style:
pattern-matches on the exception type and argument:
<langsyntaxhighlight lang="haskell">do
{- do IO computations here -}
`catch` \ex -> do
{- handle exception "ex" here -}</langsyntaxhighlight>
 
Note: Control.Exception's "catch" is different than Prelude's "catch".
 
To catch a user-defined exception, use "catchDyn":
<langsyntaxhighlight lang="haskell">do
{- do IO computations here -}
`catchDyn` \ex -> do
{- handle exception "ex" here -}</langsyntaxhighlight>
 
=={{header|HolyC}}==
Line 1,289 ⟶ 1,352:
The <code>catch</code> block does not have the capability to differentiate between specific exceptions. Instead, all exceptions for a <code>try</code> block are handled by a single <code>catch</code> block.
 
<langsyntaxhighlight lang="holyc">try {
U8 *err = 'Error';
throw(err); // throw exception
Line 1,296 ⟶ 1,359:
Print("Raised 'Error'");
PutExcept; // print the exception and stack trace
}</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 1,306 ⟶ 1,369:
support exceptions.</i>
 
<langsyntaxhighlight Uniconlang="unicon">import Exceptions
 
procedure main(A)
Line 1,322 ⟶ 1,385:
if numeric(i) = 3 then Exception().throw("bad value of "||i)
return i
end</langsyntaxhighlight>
 
A sample run is:
Line 1,348 ⟶ 1,411:
An exception in an explicit definition can be detected with <tt>try.</tt> and <tt>catcht.</tt> and can be thrown with <tt> throw. </tt> as seen below.
 
<langsyntaxhighlight lang="j"> pickyPicky =: verb define
if. y-:'bad argument' do.
throw.
Line 1,365 ⟶ 1,428:
 
tryThis 'bad argument'
Uh oh!</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,371 ⟶ 1,434:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="java">//Checked exception
public class MyException extends Exception {
//Put specific info in here
Line 1,377 ⟶ 1,440:
 
//Unchecked exception
public class MyRuntimeException extends RuntimeException {}</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="java">public void fooChecked() throws MyException {
throw new MyException();
}
Line 1,386 ⟶ 1,449:
public void fooUnchecked() {
throw new MyRuntimeException();
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="java">try {
fooChecked();
}
Line 1,403 ⟶ 1,466:
finally {
//This code is always executed after exiting the try block
}</langsyntaxhighlight>
{{works with|Java|7+}}
Java 7 added "multicatch" and "smart rethrow".
<langsyntaxhighlight lang="java5">public void foo() throws UnsupportedDataTypeException{
try{
throwsNumberFormatException();
Line 1,418 ⟶ 1,481:
throw e;
}
}</langsyntaxhighlight>
In previous versions of Java, <code>foo()</code> would have to declare that it throws an <code>IOException</code>. The "smart rethrow" recognizes that the only checked exception that can result in the rethrow ("<code>throw e;</code>") is an <code>UnsupportedDataTypeException</code>. The last catch block will still catch any other unchecked <code>IOException</code>s and rethrow them, but <code>foo()</code> only needs to declare that <code>UnsupportedDataTypeException</code>s are thrown from it since that's the only checked exception that can cause a rethrow.
 
Line 1,427 ⟶ 1,490:
'''Throwing exceptions'''
 
<langsyntaxhighlight lang="javascript">function doStuff() {
throw new Error('Not implemented!');
}</langsyntaxhighlight>
 
'''Catching exceptions'''
 
<langsyntaxhighlight lang="javascript">try {
element.attachEvent('onclick', doStuff);
}
Line 1,441 ⟶ 1,504:
finally {
eventSetup = true;
}</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|>1.4}}
Line 1,450 ⟶ 1,514:
 
The "try" clause takes the form:
<syntaxhighlight lang ="jq">try FILTER catch CATCHER</langsyntaxhighlight>
where FILTER and CATCHER may be any jq expressions.
 
Line 1,456 ⟶ 1,520:
 
'''Example''':
<langsyntaxhighlight lang="jq">def division(a;b):
def abs: if . < 0 then -. else . end;
if a == 0 and b == 0 then error("0/0")
Line 1,469 ⟶ 1,533:
elif . == "division by 0" then null
else "\(.): \(a) / \(b)"
end;</langsyntaxhighlight>
 
# test(0;0) # produces 0
Line 1,478 ⟶ 1,542:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function extendedsqrt(x)
try sqrt(x)
catch
Line 1,491 ⟶ 1,555:
@show extendedsqrt(1) # 1
@show extendedsqrt(-1) # 0.0 + 1.0im
@show extendedsqrt('x') # ERROR: DomainError</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
// In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception'
Line 1,516 ⟶ 1,580:
fun main(args: Array<String>) {
goo()
}</langsyntaxhighlight>
 
{{out}}
Line 1,530 ⟶ 1,594:
</pre>
 
=={{header|Langurlangur}}==
Exceptions in langur are hashes guaranteed to contain certain fields, even if they're empty.
 
A catch causes all the statements preceding it within a block to be the implicit try block.
 
Exceptions in langur are hashes guaranteed to contain certain fields, even if they're empty.
An else section on a catch is optional (available from version 0.5.0 and higher).
 
<syntaxhighlight lang="langur">throw "not a math exception"
<lang Langur># do something
throw "not a math exception"
 
catch [.e] {
if .e["'cat"] == "math" {
# change result...
} else {
Line 1,549 ⟶ 1,610:
} else {
# no exception
}
...
</syntaxhighlight>
}</lang>
 
An else section on a catch is optional. You can also use else if.
=== shortened catch ===
A catch can be shortened by using a single expression that does not start with a variable name. This uses the implicit .err exception variable.
 
=== exception variable ===
A shortened catch does not allow an else section (action for no exception).
An exception variable may be specified, or you can simply use the implicit variable, which is _err.
 
<syntaxhighlight lang="langur">100 / 0
<lang Langur>catch if .err["cat"] == "math" {
 
# change result
} elsecatch {
if _err'cat == "math" {
throw
# change result
}</lang>
123
} else {
# rethrow the exception
throw
}
}
</syntaxhighlight>
 
<langsyntaxhighlight Langurlang="langur">val .safediv = ffn(.x, .y) { .x / .y ; catch : 0 }
.safediv(7, 7) # 1
.safediv(7, 0) # 0</lang>
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">protect => {
handle_error => {
// do something else
}
fail(-1,'Oops')
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
Lingo has no try...catch mechanism. A script error will always end execution of the current call stack. There is however a mechanism that prevents that script errors quit the execution of the current movie/projector: you can set up an "alertHook" that is called when such errors occur. This alertHook can then e.g. log the error to a file or database, and if it returns 1, the movie/projector continues to play:
 
<langsyntaxhighlight lang="lingo">-- parent script "ErrorHandler"
 
on alertHook (me, errorType, errorMessage, alertType)
Line 1,596 ⟶ 1,665:
 
return 1 -- continues movie playback, no error dialog
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">-- in a movie script
on prepareMovie
_player.alertHook = script("ErrorHandler")
end</langsyntaxhighlight>
 
In terms of the behavior described above, a "throw" command triggering custom errors that behave exactly like real script errors can be implemented like this:
 
<langsyntaxhighlight lang="lingo">-- in a movie script
-- usage: throw("Custom error 23")
on throw (msg)
_player.alertHook.alertHook("Script runtime error", msg, #script)
abort() -- exits call stack
end</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to div.checked :a :b
if :b = 0 [(throw "divzero 0)]
output :a / :b
Line 1,620 ⟶ 1,689:
to div.safely :a :b
output catch "divzero [div.checked :a :b]
end</langsyntaxhighlight>
There are also some predefined exceptions:
* '''throw "toplevel''' returns to the interactive prompt if uncaught (like control-C)
Line 1,629 ⟶ 1,698:
=={{header|Logtalk}}==
Logtalk exception-handling mechanism is based on the catch/3 and throw/1 predicates inherited from Prolog:
<langsyntaxhighlight lang="logtalk">
:- object(exceptions).
 
Line 1,653 ⟶ 1,722:
 
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,670 ⟶ 1,739:
=={{header|Lua}}==
'''Throwing an Exception'''<br>
<syntaxhighlight lang="lua">
<lang Lua>
error("Something bad happened!")
</syntaxhighlight>
</lang>
 
'''Catching Exceptions'''<br>
<syntaxhighlight lang="lua">
<lang Lua>
function throw_error()
error("Whoops")
Line 1,687 ⟶ 1,756:
status, errmsg = pcall(throw_error)
print("errmsg = ", errmsg)
</syntaxhighlight>
</lang>
 
Note that `pcall` passes every argument after the function object or function name to said function:<br />
<syntaxhighlight lang="lua">
<lang Lua>
function throw_error_with_argment(argument)
error(string.format("Whoops! argument = %s", argument))
Line 1,699 ⟶ 1,768:
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)
</syntaxhighlight>
</lang>
 
If a function does not throw an error, 'errmsg' (which might be called 'returned' as well) contains the value(s) returned from the function:<br />
<syntaxhighlight lang="lua">
<lang Lua>
function throw_error_with_argment(argument)
return "hello!"
Line 1,709 ⟶ 1,778:
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Errors {
Module Check {
Line 1,734 ⟶ 1,804:
Errors
Print Error$=""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,749 ⟶ 1,819:
fail.mk
 
<langsyntaxhighlight lang="make">all:
false</langsyntaxhighlight>
 
Using -@ to ignore the exception.
Line 1,756 ⟶ 1,826:
catch.mk
 
<langsyntaxhighlight lang="make">all:
-@make -f fail.mk</langsyntaxhighlight>
 
Using explicit exit 0 to ignore the exception.
Line 1,763 ⟶ 1,833:
catch.mk
 
<langsyntaxhighlight lang="make">all:
make -f fail.mk; exit 0</langsyntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
errorproc:=proc(n)
local a;
Line 1,776 ⟶ 1,846:
end try;
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">f[x_] := If[x > 10, Throw[overflow], x!]
 
Example usage :
Line 1,786 ⟶ 1,856:
 
Catch[f[2] + f[3]]
-> 8</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 1,792 ⟶ 1,862:
 
Sample usage:
<langsyntaxhighlight MATLABlang="matlab">>> error 'Help'
??? Help</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Line 1,799 ⟶ 1,869:
'''Defining exceptions'''<br>
Exceptions can only be declared at the "top-level" of a module or interface. Arguments are optional.
<langsyntaxhighlight lang="modula3">EXCEPTION EndOfFile;
EXCEPTION Error(TEXT);</langsyntaxhighlight>
 
'''Throw exceptions'''<br>
Exceptions can be bound to procedures using RAISES:
<langsyntaxhighlight lang="modula3">PROCEDURE Foo() RAISES { EndOfFile } =
...
RAISE EndOfFile;
...</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="modula3">TRY
Foo();
EXCEPT
| EndOfFile => HandleFoo();
END;</langsyntaxhighlight>
 
Modula-3 also has a FINALLY keyword:
<langsyntaxhighlight lang="modula3">TRY
Foo();
FINALLY
CleanupFoo(); (* always executed *)
END;</langsyntaxhighlight>
 
 
=={{header|MOO}}==
Line 1,828 ⟶ 1,897:
'''Throw exceptions'''<br>
Values can be raised to exceptions using raise():
<syntaxhighlight lang ="moo">raise(E_PERM);</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="moo">try
this:foo();
except e (ANY)
this:bar(e);
endtry</langsyntaxhighlight>
 
MOO also has a finally statement:
<langsyntaxhighlight lang="moo">try
this:foo();
finally
this:bar();
endtry</langsyntaxhighlight>
 
'''Shorthand'''
<langsyntaxhighlight lang="moo">`this:foo()!ANY=>this:bar()';</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">try
invalid "this statement will fail"
catch e
println "caught an exception"
println e
end try</langsyntaxhighlight>
Throwing exceptions:
<langsyntaxhighlight lang="nanoquery">throw new(Exception, "exception reason as string")</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">// define a new exception
class MyException : Exception
{
Line 1,880 ⟶ 1,949:
finally {
... // code executes whether or not exception was thrown
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
As <tt>NetRexx</tt> runs under the control of a JVM it has the same exception model as [[#Java|Java]].
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,912 ⟶ 1,981:
super('I resent that!')
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,920 ⟶ 1,989:
=={{header|Nim}}==
'''Defining exceptions'''
<langsyntaxhighlight lang="nim">type SillyError = object of Exception</langsyntaxhighlight>
'''Throwing an exception'''
<langsyntaxhighlight lang="nim">proc spam() =
raise newException(SillyError, "Some error")</langsyntaxhighlight>
'''Handling an exception'''
<langsyntaxhighlight lang="nim">try:
spam()
except SillyError:
Line 1,932 ⟶ 2,001:
echo "Got another exception"
finally:
echo "Finally"</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 1,938 ⟶ 2,007:
'''Defining exceptions'''<br>
Exceptions can be any Objective-C object, though they are usually instances of <code>NSException</code>. You can create a subclass of NSException if necessary:
<langsyntaxhighlight lang="objc">@interface MyException : NSException {
//Put specific info in here
}
@end</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="objc">- (void)foo {
@throw [NSException exceptionWithName:@"TerribleException"
reason:@"OMGWTFBBQ111!1" userInfo:nil];
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="objc">@try {
[self foo];
}
Line 1,965 ⟶ 2,034:
@finally {
//This code is always executed after exiting the try block
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,971 ⟶ 2,040:
'''Defining exceptions'''<br>
Like constructors, exceptions may or may not have an argument:
<langsyntaxhighlight lang="ocaml">exception My_Exception;;
exception Another_Exception of string;;</langsyntaxhighlight>
 
'''Throw exceptions'''<br>
Throw exceptions with the "raise" function; the expression will match any type:
<langsyntaxhighlight lang="ocaml">let foo x =
match x with
1 -> raise My_Exception
| 2 -> raise (Another_Exception "hi mom")
| _ -> 5
;;</langsyntaxhighlight>
 
'''Catching exceptions'''<br>
The "with" syntax pattern-matches on the exception type and argument:
<langsyntaxhighlight lang="ocaml">try
string_of_int (foo 2)
with
My_Exception -> "got my exception"
| Another_Exception s -> s
| _ -> "unknown exception"</langsyntaxhighlight>
 
 
=={{header|Oforth}}==
Line 1,999 ⟶ 2,067:
It is also possible to create new exception classes (see Exception.of).
 
<langsyntaxhighlight Oforthlang="oforth">: iwillThrowAnException "A new exception" Exception throw ;
: iwillCatch
Line 2,005 ⟶ 2,073:
try: e [ iwillThrowAnException ] when: [ "Exception catched :" . e .cr ]
try: e [ 1 2 over last ] when: [ "Exception catched :" . e .cr ]
"Done" println ;</langsyntaxhighlight>
 
{{out}}
Line 2,018 ⟶ 2,086:
'''Throw exceptions'''<br>
Any value can be thrown as an exception. Typically record values are used.
<langsyntaxhighlight lang="oz">raise sillyError end
raise slightlyLessSilly(data:42 reason:outOfMemory) end</langsyntaxhighlight>
 
By using a record value with a feature <code>debug</code> set to <code>unit</code> you can indicate that the exception shall have debug information (including a stack trace).
 
<langsyntaxhighlight lang="oz">try
raise someError(debug:unit) end
catch someError(debug:d(stack:ST ...)...) then
{Inspect ST}
end</langsyntaxhighlight>
 
See also: [http://www.mozart-oz.org/documentation/base/exception.html Exceptions] in the Oz documentation.
Line 2,033 ⟶ 2,101:
'''Catching exceptions'''<br>
Exception are caught with pattern matching. Ellipsis indicating additional optional fields are often useful here.
<langsyntaxhighlight lang="oz">try
{Foo}
catch sillyError then
Line 2,043 ⟶ 2,111:
finally
{Fin}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 2,074 ⟶ 2,142:
|User-initiated error
|}
<langsyntaxhighlight lang="parigp">trap(/* specific error can be given here, or leave blank to catch all */,
"caught"
,
error("bad stuff")
)</langsyntaxhighlight>
 
===Throwing errors in GP===
The only error that can be thrown in GP is user error:
<langsyntaxhighlight lang="parigp">error("Text of error here")</langsyntaxhighlight>
 
===Throwing errors in PARI===
Line 2,185 ⟶ 2,253:
|}
</div>
<langsyntaxhighlight Clang="c">pari_err(arither1, "functionName"); // Gives "*** functionName: not an integer argument in an arithmetic function"</langsyntaxhighlight>
 
===Catching errors in PARI===
It is rare that this mechanism needs to be used in PARI, rather than standard [[#C|C]] methods, but the function <code>closure_trapgen</code> (similar to <code>closure_evalgen</code>) is available:
<langsyntaxhighlight Clang="c">GEN x = closure_trapgen(arither1, f); // Executes the function f, catching "not an integer argument in an arithmetic function" errors
if (x == (GEN)1L) // Was there an error?
pari_printf("Don't do that!\n"); // Recover</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,201 ⟶ 2,269:
Exceptions using the core [http://perldoc.perl.org/functions/eval.html eval] function:
 
<langsyntaxhighlight lang="perl"># throw an exception
die "Danger, danger, Will Robinson!";
 
Line 2,211 ⟶ 2,279:
 
# rethrow
die $@;</langsyntaxhighlight>
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable <tt>$@</tt>. See http://search.cpan.org/dist/Error for advanced object based-exception handling.
Line 2,218 ⟶ 2,286:
The same using the [http://search.cpan.org/perldoc?Try::Tiny Try::Tiny] module:
 
<langsyntaxhighlight lang="perl"># throw an exception
die "Danger, danger, Will Robinson!";</langsyntaxhighlight>
<langsyntaxhighlight lang="perl"># catch an exception and show it
try {
die "this could go wrong mightily";
} catch {
print;
};</langsyntaxhighlight>
<langsyntaxhighlight lang="perl"># rethrow (inside of catch)
die $_;</langsyntaxhighlight>
 
'''Other styles'''<br>
More complicated exception handling can be achieved in Perl using [http://search.cpan.org/perldoc?TryCatch TryCatch] or [http://search.cpan.org/perldoc?Exception::Class Exception::Class] modules.
 
=={{header|Perl 6}}==
{{works with|rakudo|2015-09-10}}
The Perl 6 equivalent to Perl 5's eval {...} is try {...}. A try block by default has a CATCH block that handles all fatal exceptions by ignoring them. If you define a CATCH block within the try, it replaces the default CATCH. It also makes the try keyword redundant, because any block can function as a try block if you put a CATCH block within it. The inside of a CATCH functions as a switch statement on the current exception.
<lang perl6>try {
die "Help I'm dieing!";
CATCH {
when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" }
default { note "Unexpected exception, $_!" }
}
}
 
say "Yay. I'm alive.";
 
die "I'm dead.";
 
say "Arrgh.";
 
CATCH {
default { note "No you're not."; say $_.Str; }
}</lang>
 
<pre>
HELP I'M DIEING!
Cough, Cough, Aiee!!
Yay. I'm alive.
No you're not.
I'm dead.
</pre>
 
Perl 6 comes with [http://design.perl6.org/S04.html#Phasers phasers], that are called when certain conditions in the life of a program, routine or block are met. <tt>CATCH</tt> is one of them and works nicely together with <tt>LEAVE</tt> that is called even if an exception would force the current block to be left immediately. It's a nice place to put your cleanup code.
 
<lang perl6>sub f(){
ENTER { note '1) f has been entered' }
LEAVE { note '2) f has been left' }
say '3) here be dragons';
die '4) that happend to be deadly';
}
 
f();
say '5) am I alive?';
 
CATCH {
when X::AdHoc { note q{6) no, I'm dead}; }
}</lang>
 
<pre>1) f has been entered
3) here be dragons
6) no, I'm dead
2) f has been left</pre>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix provides try/catch and throw statements.
 
'''Throwing exceptions'''<br>
You can throw any string (on it's own) or any integer, optionally with any (deeply nested) user_data that you like.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>throw("oh no")
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #008000;">"oh no"<span style="color: #0000FF;">)</span>
throw(1)
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span>
throw(501,{"she",made[me],Do(it)})</lang>
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">501<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #008000;">"she"<span style="color: #0000FF;">,<span style="color: #000000;">made<span style="color: #0000FF;">[<span style="color: #000000;">me<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">Do<span style="color: #0000FF;">(<span style="color: #000000;">it<span style="color: #0000FF;">)<span style="color: #0000FF;">}<span style="color: #0000FF;">)
<!--</syntaxhighlight>-->
 
'''Catching exceptions'''<br>
There is one and only one non-optional catch clause per try statement. <br>
The variable caught is a sequence, augmented with run-time diagnostics, with whatever was thrown in e[E_CODE] and/or e[E_USER].
<!--<syntaxhighlight lang="phix">-->
<lang Phix>try
<span style="color: #008080;">try</span>
one_of(these)
<span style="color: #000000;">one_of<span style="color: #0000FF;">(<span style="color: #000000;">these<span style="color: #0000FF;">)</span>
catch e
<span style="color: #008080;">catch</span> <span style="color: #000000;">e</span>
if e[E_CODE]=501 then
<span style="color: #008080;">if</span> <span style="color: #000000;">e<span style="color: #0000FF;">[<span style="color: #000000;">E_CODE<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">501</span> <span style="color: #008080;">then</span>
puts(1,"that's no excuse!\n")
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"that's no excuse!\n"<span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">else</span>
throw(e)
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">e<span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end try</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">try
<!--</syntaxhighlight>-->
 
An uncaught exception terminates the program in error, otherwise control resumes in the catch clause or after the end try,
with no means (apart from some really nasty inline assembly) of resuming any half-finished block of code, and indeed any
call stack entries between a throw and a catch will already have been torn down and thrown away.<br>
Traditionally fatal errors are re-routed via throw() when the presence of an exception handler is detected.<br>
There is no absurdly confusing finally construct (- trivial to <del>mimic</del> better with the introduction of a single simple boolean flag anyway).
 
=={{header|PHL}}==
Line 2,313 ⟶ 2,337:
PHL does not support multiple catch-clauses.
 
<langsyntaxhighlight lang="phl">module exceptions;
 
extern printf;
Line 2,335 ⟶ 2,359:
}
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
Line 2,344 ⟶ 2,368:
 
'''Define exceptions'''
<langsyntaxhighlight lang="php">class MyException extends Exception
{
// Custom exception attributes & methods
}</langsyntaxhighlight>
 
'''Throwing exceptions'''
<langsyntaxhighlight lang="php">function throwsException()
{
throw new Exception('Exception message');
}</langsyntaxhighlight>
 
'''Catching Exceptions'''
<langsyntaxhighlight lang="php">try {
throwsException();
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 2,368 ⟶ 2,392:
'throw' will transfer control to a 'catch' environment
that was set up with the given label.
<langsyntaxhighlight PicoLisplang="picolisp">(catch 'thisLabel # Catch this label
(println 1) # Do some processing (print '1')
(throw 'thisLabel 2) # Abort processing and return '2'
(println 3) ) # This is never reached</langsyntaxhighlight>
{{out}}
<pre>1 # '1' is printed
Line 2,377 ⟶ 2,401:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
/* Define a new exception, called "my_condition". */
on condition (my_condition) snap begin;
Line 2,389 ⟶ 2,413:
/* to be printed, and execution then resumes at the statement */
/* following the SIGNAL statement. */
</syntaxhighlight>
</lang>
 
=={{header|PL/pgSQL}}==
 
'''Raise an exception'''
<syntaxhighlight lang="sql">
<lang SQL>
begin
raise exception 'this is a generic user exception';
raise exception division_by_zero;
end;
</syntaxhighlight>
</lang>
 
'''Handle an exception'''
 
Hande division by zero and re-raising once caught other exception:
<syntaxhighlight lang="sql">
<lang SQL>
create function special_division(p_num double precision, p_den double precision) returns text
as $body$
Line 2,421 ⟶ 2,445:
raise;
end;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 2,427 ⟶ 2,451:
'''Throwing exceptions'''
 
<langsyntaxhighlight lang="pop11">define throw_exception();
throw([my_exception my_data]);
enddefine;</langsyntaxhighlight>
 
'''Catching exceptions'''
 
<langsyntaxhighlight lang="pop11">define main();
vars cargo;
define catcher();
Line 2,442 ⟶ 2,466:
enddefine;
 
main();</langsyntaxhighlight>
 
=={{header|PowerShell}}==
'''Throw an exception:'''
<syntaxhighlight lang="powershell">
<lang PowerShell>
throw "Any error message."
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,459 ⟶ 2,483:
</pre>
'''Throw a more specific exception:'''
<syntaxhighlight lang="powershell">
<lang PowerShell>
throw [System.IO.FileNotFoundException] ".\temp.txt not found."
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,472 ⟶ 2,496:
</pre>
'''Using <code>try {} catch {}</code> is better for more complex error checking because you can test specific errors:'''
<syntaxhighlight lang="powershell">
<lang PowerShell>
try
{
Line 2,485 ⟶ 2,509:
Write-Host "Other exception"
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,496 ⟶ 2,520:
</pre>
'''Errors are objects like any other in PowerShell, so you may capture any detail of it:'''
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Error[0] | Get-Member
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,523 ⟶ 2,547:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">foo(X) :-
\+ integer(X),
throw(b('not even an int')).
Line 2,541 ⟶ 2,565:
format('~w~n', Msg),
!.
handle(X) :- throw(X).</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,562 ⟶ 2,586:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure ErrorHandler()
MessageRequester("Exception test", "The following error happened: " + ErrorMessage())
EndProcedure
Line 2,570 ⟶ 2,594:
OnErrorCall(@ErrorHandler())
 
RaiseError(#PB_OnError_InvalidMemory) ;a custom error# can also be used here depending on the OS being compiled for</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,576 ⟶ 2,600:
'''Defining an exception'''
 
<langsyntaxhighlight lang="python">import exceptions
class SillyError(exceptions.Exception):
def __init__(self,args=None):
self.args=args</langsyntaxhighlight>
 
Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:
 
<langsyntaxhighlight lang="python">class MyInvalidArgument(ValueError):
pass</langsyntaxhighlight>
 
This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
Line 2,592 ⟶ 2,616:
 
Creating an exception using the default constructor of an exception class:
<langsyntaxhighlight lang="python">def spam():
raise SillyError # equivalent to raise SillyError()</langsyntaxhighlight>
 
{{works with|Python|2.5}}
 
Passing an argument to the constructor of an exception class:
<langsyntaxhighlight lang="python">def spam():
raise SillyError, 'egg' # equivalent to raise SillyError('egg')</langsyntaxhighlight>
The above syntax is removed in Python 3.0; but the following syntax works in Python 2.x and 3.x, so should be preferred.
 
{{works with|Python|2.x and 3.x}}
<langsyntaxhighlight lang="python">def spam():
raise SillyError('egg')</langsyntaxhighlight>
 
'''Handling an exception'''<br>
Line 2,611 ⟶ 2,635:
try-except-else-finally
 
<langsyntaxhighlight lang="python">try:
foo()
except SillyError, se:
Line 2,620 ⟶ 2,644:
quux()
finally:
baz()</langsyntaxhighlight>
 
Before Python 2.5 it was not possible to use finally and except together. (It was necessary to nest a separate ''try''...''except'' block inside of your ''try''...''finally'' block).
Line 2,627 ⟶ 2,651:
 
Note: Python3 will change the syntax of except slightly, but in a way that is not backwards compatible. In Python 2.x and earlier the ''except'' statement could list a single exception or a tuple/list of exceptions and optionally a name to which the exception object will be bound. In the old versions the exception's name followed a comma (as in the foregoing example). In Python3 the syntax will become: ''except Exception1 [,Exception2 ...] '''as''' ExceptionName''
<langsyntaxhighlight lang="python">try:
foo()
except SillyError as se:
Line 2,636 ⟶ 2,660:
quux()
finally:
baz()</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
As the overwhelming majority of Quackery is open and accessible to the programmer Exception Handling cannot be fully automated. The full explanation is contained in The Book of Quackery, downloadable as a pdf from [https://github.com/GordonCharlton/Quackery the GitHub Quackery repository], section Word Behaviours, subsection Exception Handling.
 
Here we will consider "typical" usage, which will restore as much of the system state as is usually required when an exception is raised. (i.e. excluding the compiler's dictionaries, and not including any special actions to compensate for breaches of the conventions which Quackery has instead of strictly enforced rules.)
 
Consider a Quackery word <code>a</code> composed of other Quackery words to an arbitrary level of nesting, and somewhere within that code a condition is detected which requires one to backtrack to just before <code>a</code> was invoked, and follow an alternate path, <code>b</code>. Additionally, some information regarding the reason for bailing out of <code>a</code> is required, for example a string of text describing the reason for abandoning path <code>a</code>.
 
When the condition is detected, <code>a</code>, or one of the words it invokes, will put a suitable message on the system ancillary stack called <code>message</code>, and invoke the word <code>bail</code>.
 
<syntaxhighlight lang="quackery"> <flag on stack indicating if condition detected>
if [ $ "It all went pear shaped in 'a'." message put bail ]</syntaxhighlight>
 
The one piece of necessary information about changes to the system state that Quackery cannot infer, even in "typical" usage, is the maximum number of items on the stack that may be removed or replaced during the execution of <code>a</code>. This needs to be specified by the programmer. (If the programmer is following conventions about stack comments, this could be gleaned from <code>a</code>'s stack comment, but Quackery steadfastly disregards all comments.) In this example, <code>a</code> consumes three stack items, so that is included in the code. How many it returns if there is no exception raised is not necessary information.
 
<syntaxhighlight lang="quackery"> 3 backup a bailed if [ message take echo$ b ]</syntaxhighlight>
 
<code>backup</code> makes a copy of the 3 topmost items on the stack and performs other necessary actions to ensure that the system state can be restored if <code>bail</code> is invoked during the execution of <code>a</code>.
 
If <code>bail</code> is not invoked, <code>bailed</code> disposes of the state information saved by <code>backup</code> and leaves <code>false</code> on the stack, so the nest following <code>if</code> is not executed.
 
If <code>bail</code> is invoked, <code>bailed</code> restores the system state and leaves <code>true</code> on the stack, so the nest following <code>if</code> is executed, in this example printing the text <code>It all went pear shaped in 'a'.</code> on the screen and executing the Quackery word <code>b</code>.
 
=={{header|R}}==
 
'''Define an exception'''
<syntaxhighlight lang="r">
<lang r>
e <- simpleError("This is a simpleError")
</syntaxhighlight>
</lang>
 
'''Raise an exception'''
<syntaxhighlight lang="r">
<lang r>
stop("An error has occured")
stop(e) #where e is a simpleError, as above
</syntaxhighlight>
</lang>
 
'''Handle an exception'''
<syntaxhighlight lang="r">
<lang r>
tryCatch(
{
Line 2,666 ⟶ 2,713:
finally = message("This is called whether or not an exception occured")
)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,684 ⟶ 2,731:
;; raise the exception
(raise (exn:my-exception "Hi!" (current-continuation-marks))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-10}}
The Raku equivalent to Perl 5's eval {...} is try {...}. A try block by default has a CATCH block that handles all fatal exceptions by ignoring them. If you define a CATCH block within the try, it replaces the default CATCH. It also makes the try keyword redundant, because any block can function as a try block if you put a CATCH block within it. The inside of a CATCH functions as a switch statement on the current exception.
<syntaxhighlight lang="raku" line>try {
die "Help I'm dieing!";
CATCH {
when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" }
default { note "Unexpected exception, $_!" }
}
}
 
say "Yay. I'm alive.";
 
die "I'm dead.";
 
say "Arrgh.";
 
CATCH {
default { note "No you're not."; say $_.Str; }
}</syntaxhighlight>
 
<pre>
HELP I'M DIEING!
Cough, Cough, Aiee!!
Yay. I'm alive.
No you're not.
I'm dead.
</pre>
 
Rake comes with [http://design.raku.org/S04.html#Phasers phasers], that are called when certain conditions in the life of a program, routine or block are met. <tt>CATCH</tt> is one of them and works nicely together with <tt>LEAVE</tt> that is called even if an exception would force the current block to be left immediately. It's a nice place to put your cleanup code.
 
<syntaxhighlight lang="raku" line>sub f(){
ENTER { note '1) f has been entered' }
LEAVE { note '2) f has been left' }
say '3) here be dragons';
die '4) that happend to be deadly';
}
 
f();
say '5) am I alive?';
 
CATCH {
when X::AdHoc { note q{6) no, I'm dead}; }
}</syntaxhighlight>
 
<pre>1) f has been entered
3) here be dragons
6) no, I'm dead
2) f has been left</pre>
 
=={{header|Raven}}==
 
<langsyntaxhighlight lang="raven">42 as custom_error
 
define foo
Line 2,697 ⟶ 2,795:
catch
custom_error =
if 'oops' print</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,704 ⟶ 2,802:
This type of exception handling (in REXX) has its limitation
(the label is local to the program, not external subroutines).
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates handling an exception (negative #); catching is via a label.*/
do j=9 by -5
say 'the square root of ' j " is " sqrt(j)
Line 2,716 ⟶ 2,814:
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/
numeric digits d; return g/1
.sqrtNeg: say 'illegal SQRT argument (argument is negative):' x; exit 13</langsyntaxhighlight>
'''output'''
<pre>
Line 2,725 ⟶ 2,823:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Try
see 1/0
Catch
raise("Sorry we can't divide 1/0" + nl)
Done
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
Basic RPL allows a conditional branching on error:
≪ '''IFERR''' '1/0' EVAL '''THEN'''
<span style="color:red">"Can't divide "</span> ROT →STR + <span style="color:red">" by "</span> + SWAP →STR + '''END'''
 
=={{header|Ruby}}==
Line 2,737 ⟶ 2,841:
'''Defining an exception'''
 
<langsyntaxhighlight lang="ruby"># define an exception
class SillyError < Exception
end</langsyntaxhighlight>
 
SillyError is simply declared as a subclass of Exception. No over-riding is necessary.
 
<langsyntaxhighlight lang="ruby">class MyInvalidArgument < ArgumentError
end</langsyntaxhighlight>
 
MyInvalidArgument is a type of ArgumentError (a built-in class). A rescue clause for ArgumentError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception.
Line 2,750 ⟶ 2,854:
'''Handling an exception'''
 
<langsyntaxhighlight lang="ruby">
# raise (throw) an exception
def spam
Line 2,761 ⟶ 2,865:
rescue SillyError => se
puts se # writes 'egg' to stdout
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">begin
foo
rescue ArgumentError => e
Line 2,777 ⟶ 2,881:
# always runs
baz
end</langsyntaxhighlight>
 
ArgumentError is a type of StandardError, but Ruby uses the first matching "rescue" clause. So we never "quack" for an ArgumentError, but we only "bar" for it.
Line 2,783 ⟶ 2,887:
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages.
 
<langsyntaxhighlight lang="ruby"># short way to rescue any StandardError
quotient = 1 / 0 rescue "sorry"</langsyntaxhighlight>
 
The short form "a rescue b" returns a, but if a raises a StandardError, then it returns b. (ZeroDivisionError is a subclass of StandardError.)
Line 2,792 ⟶ 2,896:
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.
 
<langsyntaxhighlight lang="ruby">def foo
throw :done
end
Line 2,798 ⟶ 2,902:
catch :done do
foo
end</langsyntaxhighlight>
 
With Ruby 1.8, you can only "throw" and "catch" symbols. With Ruby 1.9, you can throw and catch any object. Like exceptions, the throw can be made from a function defined elsewhere from the catch block.
Line 2,808 ⟶ 2,912:
It is illustrated by the code below:
 
<langsyntaxhighlight Rustlang="rust">// IO error is used here just as an example of an already existing
// Error
use std::io::{Error, ErrorKind};
Line 2,858 ⟶ 2,962:
panicking_function();
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,868 ⟶ 2,972:
In there are 3 main entries: object CheckingAccount, CheckingBlockingAccount and NotImplementedErrorTest to selective start this solution and demonstrate the working of exceptions and handling.
 
<langsyntaxhighlight Scalalang="scala">//Defining exceptions
class AccountBlockException extends Exception
class InsufficientFundsException(val amount: Double) extends Exception
Line 2,929 ⟶ 3,033:
object NotImplementedErrorTest extends App {
??? // Throws scala.NotImplementedError: an implementation is missing
}</langsyntaxhighlight>
 
{{out}}Running entry point CheckingAccount
Line 2,950 ⟶ 3,054:
 
=={{header|Scheme}}==
Exception handling can be created with any language supporting continuations, using as few primitves as possible, exception handling in Scheme can look like this. (But anyone wishing to continue using exceptions will abstract them into macros).<langsyntaxhighlight lang="scheme">(define (me-errors xx exception)
(if (even? xx)
xx
Line 2,971 ⟶ 3,075:
(all-ok)))
 
(display "oh my god it is ODD!")))</langsyntaxhighlight>
 
=={{header|Seed7}}==
'''Raise an exception'''<langsyntaxhighlight lang="seed7">const proc: foo is func
begin
raise RANGE_ERROR;
end func;</langsyntaxhighlight>
 
'''Handle an exception'''
<langsyntaxhighlight lang="seed7">const proc: main is func
begin
block
Line 2,988 ⟶ 3,092:
writeln("catched RANGE_ERROR");
end block;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
An exception is thrown by the ''die'' keyword, which, if not caught, it terminates the program with an appropriate exit code.
<langsyntaxhighlight lang="ruby">try {
die "I'm dead!"; # throws an exception of type 'error'
}
catch { |msg|
say "msg: #{msg}" # msg: I'm dead! at test.sf line 2.
}
catch { |type, msg|
say "type: #{type}"; # type: error
say "msg: #{msg}"; # msg: I'm dead! at test.sf line 2.
};
 
say "I'm alive...";
die "Now I'm dead!"; # this line terminates the program
say "Or am I?"; # Yes, you are!</langsyntaxhighlight>
{{out}}
<pre>
Line 3,008 ⟶ 3,111:
msg: I'm dead! at test.sf line 2.
I'm alive...
Now I'm dead! at test.sf line 109.
</pre>
 
Line 3,014 ⟶ 3,117:
'''Handling Exceptions'''
 
<langsyntaxhighlight lang="slate">se@(SceneElement traits) doWithRestart: block
[
block handlingCases: {Abort -> [| :_ | ^ Nil]}
].</langsyntaxhighlight>
 
'''Define Exceptions'''
 
<langsyntaxhighlight lang="slate">conditions define: #Abort &parents: {Restart}.
"An Abort is a Restart which exits the computation, unwinding the stack."
 
Line 3,038 ⟶ 3,141:
[
c tryHandlers
].</langsyntaxhighlight>
 
'''Throwing Exceptions'''<br>
{{lines too long|Slate}}
<langsyntaxhighlight lang="slate">(fileName endsWith: '.image') ifTrue: [error: 'Image filename specified where Slate source expected. Make sure you run slate with the -i flag to specify an image.'].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Throwing an Exception
 
<langsyntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$*"
"exit"
 
Transcript show: 'Throwing yawp'; cr.
self error: 'Yawp!'.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="shell">$ ./yawp.st
Throwing yawp
Object: nil error: Yawp!
Line 3,059 ⟶ 3,162:
Error(Exception)>>signal: (AnsiExcept.st:226)
UndefinedObject(Object)>>error: (AnsiExcept.st:1565)
UndefinedObject>>executeStatements (yawp.st:5)</langsyntaxhighlight>
 
Handling an Exception
 
<langsyntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$*"
"exit"
 
Line 3,071 ⟶ 3,174:
] on: Error do: [ :e |
Transcript show: 'Caught yawp'; cr.
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="shell">$ ./yawp.st
Throwing yawp
Caught yawp</langsyntaxhighlight>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL PL:
<langsyntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
Line 3,097 ⟶ 3,200:
END IF;
END @
</syntaxhighlight>
</lang>
The next example just raise an exception, does not wrap a raised one.
<langsyntaxhighlight lang="sql pl">
BEGIN
SIGNAL SQLSTATE '75002'
SET MESSAGE_TEXT = 'Customer number is not known';
END @
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,129 ⟶ 3,232:
 
'''Define Exceptions'''
<langsyntaxhighlight lang="sml">exception MyException;
exception MyDataException of int; (* can be any first-class type, not just int *)</langsyntaxhighlight>
 
'''Throw Exceptions'''
<langsyntaxhighlight lang="sml">fun f() = raise MyException;
fun g() = raise MyDataException 22;</langsyntaxhighlight>
 
'''Catch Exceptions'''
<langsyntaxhighlight lang="sml">val x = f() handle MyException => 22;
val y = f() handle MyDataException x => x;</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 3,149 ⟶ 3,252:
Example of usage:
 
<langsyntaxhighlight lang="stata">capture confirm file titanium.dta
if _rc {
if _rc==601 {
Line 3,158 ⟶ 3,261:
display "there was an error with return code " _rc
}
}</langsyntaxhighlight>
 
Similarly, Mata has functions '''[http://www.stata.com/help.cgi?mf_error error]''' and '''[http://www.stata.com/help.cgi?mf_exit exit]''' to terminate execution, as well as '''[http://www.stata.com/help.cgi?mf_assert assert]''' and '''asserteq'''.
Line 3,166 ⟶ 3,269:
'''Defining exceptions'''<br />
Exceptions can be of any type that conforms to the <code>ErrorType</code> protocol.
<langsyntaxhighlight lang="swift">enum MyException : ErrorType {
case TerribleException
}</langsyntaxhighlight>
 
'''Throw exceptions'''<br />
A function that throws an exception must be explicitly declared so:
<langsyntaxhighlight lang="swift">func foo() throws {
throw MyException.TerribleException
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="swift">do {
try foo()
} catch MyException.TerribleException { // this can be any pattern
Line 3,183 ⟶ 3,286:
} catch {
//Catch any exception
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Throw
Line 3,200 ⟶ 3,303:
}
 
f</langsyntaxhighlight>
This creates the stack trace
<pre>error message for stack trace
Line 3,209 ⟶ 3,312:
invoked from within
"f"</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
mainModule : {
func2: (lambda i Int()
(if (!= i 13)
(textout "OK " i "\n")
(throw "fail\n"))),
 
func1: (lambda
(textout "before try\n")
(try
(textout "before while\n")
(with n 10
(while (< n 15) (+= n 1)
(func2 n)
)
)
(textout "after while\n")
(catch (report e))
)
(textout "after try\n")
),
_start: (lambda (func1))
}
</syntaxhighlight>
OUTPUT:
---------------
<pre>
before try
before while
OK 10
OK 11
OK 12
fail
after try</pre>
 
=={{header|TXR}}==
Line 3,220 ⟶ 3,360:
In the main @(collect) clause, we have a try protect block in which we collect three different cases of primate. For each one, we throw an exception with the primate type symbol, and its name. This is caught in the catch clause as the argument "name". The catch clause performs another pattern match, @kind @name. This match is being applied to exactly the same line of data for which the exception was thrown (backtracking!). Therefore the @kind variable will collect the primate type. However @name already has a binding since it is the argument of the catch. Since it has a value already, that value has to match what is in the data. Of course, it does since it was derived from that data. The data and the variable unify against each other.
 
<langsyntaxhighlight lang="txr">@(defex gorilla ape primate)
@(defex monkey primate)
@(defex human primate)
Line 3,241 ⟶ 3,381:
@(end)@#output
@(end)@#try
@(end)@#collect</langsyntaxhighlight>
 
Sample interactive run. Here the input is typed into standard input from the tty. The output is interleaved with the input, since TXR doesn't reads ahead only as much data as it needs.
Line 3,257 ⟶ 3,397:
=={{header|Ursa}}==
Catching exceptions:
<langsyntaxhighlight lang="ursa">try
invalid "this statement will fail"
catch syntaxerror
# console.err is optional here
out "caught an exception" endl console.err
end try</langsyntaxhighlight>
Throwing exceptions:
<langsyntaxhighlight lang="ursa">throw (new ursa.exceptions.exception)</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,272 ⟶ 3,412:
raises an exception with the diagnostic message 'epic fail'.
(The diagnostic message can also be made to depend on the input.)
<langsyntaxhighlight Ursalalang="ursala">#import std
 
thrower = ~&?/'success'! -[epic fail]-!%
 
catcher = guard(thrower,---[someone failed]-)</langsyntaxhighlight>
 
If the exception is not caught, the program terminates immediately and
Line 3,285 ⟶ 3,425:
In this example, the exception handler appends some additional
verbiage to the message.
 
=={{header|V}}==
 
throwing exceptions
<langsyntaxhighlight lang="v">[myproc
['new error' 1 2 3] throw
'should not come here' puts
].</langsyntaxhighlight>
 
catching them
 
<langsyntaxhighlight lang="v">[myproc] [puts] catch
=[new error 1 2 3]</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
'''Defining exceptions'''
<lang vbnet>Class MyException
Inherits Exception
'data with info about exception
End Class</lang>
 
'''Throw exceptions'''
<lang vbnet>Sub foo()
Throw New MyException
End Sub</lang>
 
'''Catching exceptions'''
<lang vbnet>Sub bar()
Try
foo()
Catch e As MyException When e.Data.Contains("Foo")
' handle exceptions of type MyException when the exception contains specific data
Catch e As MyException
' handle exceptions of type MyException and derived exceptions
Catch e As Exception
' handle any type of exception not handled by above catches
Finally
'code here occurs whether or not there was an exception
End Try
End Sub</lang>
 
=={{header|VBA}}==
Line 3,334 ⟶ 3,446:
 
'''Throw exceptions'''
<langsyntaxhighlight lang="vb">Sub foo1()
err.raise(vbObjectError + 1050)
End Sub
Line 3,341 ⟶ 3,453:
Error vbObjectError + 1051
End Sub
</syntaxhighlight>
</lang>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="vb">Sub bar1()
'by convention, a simple handler
On Error GoTo catch
Line 3,389 ⟶ 3,501:
end_try:
'by convention, often just a drop through from the catch block
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
'''Defining exceptions'''
<syntaxhighlight lang="vbnet">Class MyException
Inherits Exception
'data with info about exception
End Class</syntaxhighlight>
 
'''Throw exceptions'''
<syntaxhighlight lang="vbnet">Sub foo()
Throw New MyException
End Sub</syntaxhighlight>
 
'''Catching exceptions'''
<syntaxhighlight lang="vbnet">Sub bar()
Try
foo()
Catch e As MyException When e.Data.Contains("Foo")
' handle exceptions of type MyException when the exception contains specific data
Catch e As MyException
' handle exceptions of type MyException and derived exceptions
Catch e As Exception
' handle any type of exception not handled by above catches
Finally
'code here occurs whether or not there was an exception
End Try
End Sub</syntaxhighlight>
 
=={{header|Wren}}==
Wren doesn't have exceptions as such but we can simulate them by trying to run code which may cause an error in a fiber and then capturing any error that does occur.
 
Errors can be thrown by calling the Fiber.abort method. The VM will also call this method automatically if a runtime error occurs such as attempting to call a function that doesn't exist.
 
Here's an example of all this.
<syntaxhighlight lang="wren">var intDiv = Fn.new { |a, b|
if (!(a is Num && a.isInteger) || !(b is Num && b.isInteger)) Fiber.abort("Invalid argument(s).")
if (b == 0) Fiber.abort("Division by zero error.")
if (a == 0) a = a.badMethod()
return (a/b).truncate
}
 
var a = [ [6, 2], [6, 0], [10, 5], [true, false], [0, 2] ]
for (e in a) {
var d
var f = Fiber.new { d = intDiv.call(e[0], e[1]) }
f.try()
if (f.error) {
System.print("Caught %(f.error)")
} else {
System.print("%(e[0]) / %(e[1]) = %(d)")
}
}</syntaxhighlight>
 
{{out}}
<pre>
6 / 2 = 3
Caught Division by zero error.
10 / 5 = 2
Caught Invalid argument(s).
Caught Num does not implement 'badMethod()'.
</pre>
 
=={{header|XPL0}}==
XPL0 does not have the commands throw, try and catch; nor their equivalents.
 
By default, exceptions such as divide-by-zero cause a program to abort.
That behavior is called error trapping. Robust programs disable error
trapping by passing an integer bit array to a built-in Trap intrinsic
that selectively disables about a dozen error traps (by setting their
corresponding bits to 0). The traps are often all disabled by simply
passing 'false' when a section of code is about to do something that
might cause an exception, such as accessing a disk file that might not be
available. In this case the intrinsic GetErr is called, which returns a
value indicating which error occurred; and if an error is detected, the
program can take appropriate action without simply aborting.
 
Generally, aborting on errors is suitable during the debugging stage, but
often it's the worst alternative for an end user.
 
A related intrinsic, Restart, is useful if an error is detected in a
procedure nested many levels deep. Instead of returning the error
indication up through the many levels, it can be easier to restart the
program. A call to the Rerun intrinsic distinguishes a restart from a
normal start, and that can be used to properly handle the error.
<syntaxhighlight lang "XPL0">
real A;
[Trap(false);
A:= Sqrt(-42.);
if GetErr then
Text(0, "Square root of a negative value.
");
RlOut(0, A);
]</syntaxhighlight>
{{out}}
<pre>
Square root of a negative value.
NAN</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">try{ throw(Exception.BadDay) }
catch { println(__exception," was thrown") }
fallthrough { println("No exception was thrown") }
println("OK");</langsyntaxhighlight>
{{out}}
<pre>
Line 3,402 ⟶ 3,613:
</pre>
If you want "finally" functionality, use onExit or onExitBlock:
<langsyntaxhighlight lang="zkl">fcn f(b){
try{
onExitBlock("Exit code".println);
Line 3,412 ⟶ 3,623:
}
f(False); println("--------");
f(True);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,423 ⟶ 3,634:
OK
</pre>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
// To replace exceptions, Zig has error enums to handle error states.
 
pub fn main() !void {
// writing to stdout as file descriptor might fail,
// if we are a child process and the parent process has closed it
const stdout_wr = std.io.getStdOut().writer();
try stdout_wr.writeAll("a");
// Above code is identical to
stdout_wr.writeAll("a") catch |err| return err;
stdout_wr.writeAll("a") catch |err| {
// usually std streams are leaked and the Kernel cleans them up
var stdin = std.io.getStdIn();
var stderr = std.io.getStdErr();
stdin.close();
stderr.close();
return err;
};
}</syntaxhighlight>
6

edits