Exceptions: Difference between revisions

Add page to "Flow control" category.
(add Zig example)
(Add page to "Flow control" category.)
 
(20 intermediate revisions by 12 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}}==
Line 29 ⟶ 30:
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.
 
<langsyntaxhighlight lang="asm">;syscall for creating a new file.
mov dx,offset filename
mov cx,0
Line 54 ⟶ 55:
je FileAlreadyExistsError
 
noError:</langsyntaxhighlight>
 
=={{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 83 ⟶ 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 98 ⟶ 99:
when Error : others =>
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;</langsyntaxhighlight>
 
=={{header|Aikido}}==
Line 105 ⟶ 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 113 ⟶ 114:
}
 
</syntaxhighlight>
</lang>
 
'''Throwing exceptions'''<br>
You can throw any value.
<langsyntaxhighlight lang="aikido">
if (error) {
throw "Error"
Line 127 ⟶ 128:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
'''Simple Exception Throwing'''
<langsyntaxhighlight lang="aime">void
throwing(void)
{
Line 155 ⟶ 156:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>ready to catch
Line 162 ⟶ 163:
caught!</pre>
'''Exception Types'''
<langsyntaxhighlight lang="aime">void
ft(integer a, text &s)
{
Line 200 ⟶ 201:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>aime: tmp/et1: 6: bad number
Line 220 ⟶ 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 338 ⟶ 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 385 ⟶ 386:
RESET obj scope reset;
 
"finally: raise the base unmendable event" RAISE obj eventb</langsyntaxhighlight>{{out}}
<pre>
sum sqs: +4900
Line 426 ⟶ 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 438 ⟶ 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 448 ⟶ 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 455 ⟶ 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 469 ⟶ 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 481 ⟶ 497:
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 490 ⟶ 506:
 
=={{header|blz}}==
<langsyntaxhighlight lang="blz">
try
1 / 0 # Throw an exception
Line 497 ⟶ 513:
print("An error occured!")
end
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
Line 521 ⟶ 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 537 ⟶ 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 544 ⟶ 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 551 ⟶ 582:
'''try-catch'''
 
<langsyntaxhighlight lang="c">#include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
Line 577 ⟶ 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 664 ⟶ 695:
}
 
</syntaxhighlight>
</lang>
Now all we need to do is add a finally block :) hint: it is possible
 
Line 671 ⟶ 702:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="csharp">public class MyException : Exception
{
// data with info about exception
};</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="csharp">void foo()
{
throw MyException();
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="csharp">try {
foo();
}
Line 693 ⟶ 724:
{
// handle any type of exception not handled by above catches
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 700 ⟶ 731:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="cpp">struct MyException
{
// 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>.
 
<langsyntaxhighlight lang="cpp">#include <exception>
struct MyException: std::exception
{
virtual const char* what() const noexcept { return "description"; }
}</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="cpp">void foo()
{
throw MyException();
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="cpp">try {
foo();
}
Line 736 ⟶ 767:
{
// 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 747 ⟶ 778:
(println e)
(finally
(println "always see this"))</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
Line 754 ⟶ 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 770 ⟶ 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 783 ⟶ 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 790 ⟶ 821:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
/// Throw Exceptions
Line 824 ⟶ 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 843 ⟶ 874:
raise; // Rethrowing
end;
end;</langsyntaxhighlight>
 
'''Ways to implement finally'''
<langsyntaxhighlight lang="delphi">procedure test3;
begin
try
Line 853 ⟶ 884:
ShowMessage('test3 finally');
end;
end;</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func Integer.Add(x) {
throw @NegativesNotAllowed(x) when x < 0
this + x
Line 866 ⟶ 897:
} catch {
@NegativesNotAllowed(x) => print("Negative number: \(x)")
}</langsyntaxhighlight>
 
=={{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 887 ⟶ 918:
end;
end;
end;</langsyntaxhighlight>
 
'''Ways to implement finally'''
<langsyntaxhighlight lang="delphi">procedure Test3;
begin
try
Line 897 ⟶ 928:
PrintLn('Test3 finally');
end;
end;</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
 
<langsyntaxhighlight lang="dejavu">stuff-going-wrong:
raise :value-error
 
Line 907 ⟶ 938:
stuff-going-wrong
catch value-error:
!print "Whoops!"</langsyntaxhighlight>
{{out}}
<pre>Whoops!</pre>
Line 927 ⟶ 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 941 ⟶ 972:
return ["notok", exceptionObj]
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? catching(42)
# value: ["not ok", problem: Who?]
 
Line 950 ⟶ 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 962 ⟶ 993:
The above code rewritten to use ejectors:
 
<langsyntaxhighlight lang="e">def nameOf(arg :int, ejector) {
if (arg == 43) {
return "Bob"
Line 976 ⟶ 1,007:
return ["notok", exceptionObj]
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? catching(42)
# value: ["not ok", problem: Who?]
 
Line 985 ⟶ 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 995 ⟶ 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 1,005 ⟶ 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 1,012 ⟶ 1,043:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="elena">class MyException : Exception
{
constructor new()
<= super new("MyException raised");
}</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="elena">foo()
{
MyException.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,055 ⟶ 1,090:
 
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,065 ⟶ 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,086 ⟶ 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,108 ⟶ 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,136 ⟶ 1,171:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,148 ⟶ 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,195 ⟶ 1,230:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,204 ⟶ 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,233 ⟶ 1,268:
Print Error.Text
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,248 ⟶ 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,269 ⟶ 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,285 ⟶ 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,317 ⟶ 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,324 ⟶ 1,359:
Print("Raised 'Error'");
PutExcept; // print the exception and stack trace
}</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 1,334 ⟶ 1,369:
support exceptions.</i>
 
<langsyntaxhighlight Uniconlang="unicon">import Exceptions
 
procedure main(A)
Line 1,350 ⟶ 1,385:
if numeric(i) = 3 then Exception().throw("bad value of "||i)
return i
end</langsyntaxhighlight>
 
A sample run is:
Line 1,376 ⟶ 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,393 ⟶ 1,428:
 
tryThis 'bad argument'
Uh oh!</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,399 ⟶ 1,434:
 
'''Defining exceptions'''
<langsyntaxhighlight lang="java">//Checked exception
public class MyException extends Exception {
//Put specific info in here
Line 1,405 ⟶ 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,414 ⟶ 1,449:
public void fooUnchecked() {
throw new MyRuntimeException();
}</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="java">try {
fooChecked();
}
Line 1,431 ⟶ 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,446 ⟶ 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,455 ⟶ 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,469 ⟶ 1,504:
finally {
eventSetup = true;
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,479 ⟶ 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,485 ⟶ 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,498 ⟶ 1,533:
elif . == "division by 0" then null
else "\(.): \(a) / \(b)"
end;</langsyntaxhighlight>
 
# test(0;0) # produces 0
Line 1,507 ⟶ 1,542:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function extendedsqrt(x)
try sqrt(x)
catch
Line 1,520 ⟶ 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,545 ⟶ 1,580:
fun main(args: Array<String>) {
goo()
}</langsyntaxhighlight>
 
{{out}}
Line 1,560 ⟶ 1,595:
 
=={{header|langur}}==
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.
<lang langur># do something
throw "not a math exception"
 
<syntaxhighlight lang="langur">throw "not a math exception"
catch .e {
 
if .e["cat"] == "math" {
catch[.e] {
if .e'cat == "math" {
# change result...
} else {
Line 1,576 ⟶ 1,610:
} else {
# no exception
}
...
</syntaxhighlight>
}</lang>
 
An else section on a catch is optional. As of 0.7, youYou can also use else if on a catch. The parser wraps it into the else block of the catch, so that it looks the same to the compiler and VM.
 
=== shortenedexception catchvariable ===
An exception variable may be specified, or you can simply use the implicit variable, which is _err.
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. Prior to 0.7, the implicit exception variable was .err.
 
<syntaxhighlight lang="langur">100 / 0
A shortened catch does not allow an else section (action for no exception).
 
catch {
<lang langur>100 / 0
if _err'cat == "math" {
 
# change result
catch if _err["cat"] == "math" {
# change result 123
123} else {
# rethrow the exception
} else {
throw
}
}</lang>
}
</syntaxhighlight>
 
<langsyntaxhighlight lang="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,628 ⟶ 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,652 ⟶ 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,661 ⟶ 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,685 ⟶ 1,722:
 
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,702 ⟶ 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,719 ⟶ 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,731 ⟶ 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,741 ⟶ 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,767 ⟶ 1,804:
Errors
Print Error$=""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,782 ⟶ 1,819:
fail.mk
 
<langsyntaxhighlight lang="make">all:
false</langsyntaxhighlight>
 
Using -@ to ignore the exception.
Line 1,789 ⟶ 1,826:
catch.mk
 
<langsyntaxhighlight lang="make">all:
-@make -f fail.mk</langsyntaxhighlight>
 
Using explicit exit 0 to ignore the exception.
Line 1,796 ⟶ 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,809 ⟶ 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,819 ⟶ 1,856:
 
Catch[f[2] + f[3]]
-> 8</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 1,825 ⟶ 1,862:
 
Sample usage:
<langsyntaxhighlight MATLABlang="matlab">>> error 'Help'
??? Help</langsyntaxhighlight>
 
=={{header|Modula-3}}==
Line 1,832 ⟶ 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,860 ⟶ 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,912 ⟶ 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,944 ⟶ 1,981:
super('I resent that!')
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,952 ⟶ 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,964 ⟶ 2,001:
echo "Got another exception"
finally:
echo "Finally"</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 1,970 ⟶ 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,997 ⟶ 2,034:
@finally {
//This code is always executed after exiting the try block
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,003 ⟶ 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 2,030 ⟶ 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,036 ⟶ 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,049 ⟶ 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,064 ⟶ 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,074 ⟶ 2,111:
finally
{Fin}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 2,105 ⟶ 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,216 ⟶ 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,232 ⟶ 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,242 ⟶ 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,249 ⟶ 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>
Line 2,269 ⟶ 2,306:
'''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.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #008000;">"oh no"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span>
<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;">)
<!--</langsyntaxhighlight>-->
 
'''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].
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">try</span>
<span style="color: #000000;">one_of<span style="color: #0000FF;">(<span style="color: #000000;">these<span style="color: #0000FF;">)</span>
Line 2,288 ⟶ 2,325:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">try
<!--</langsyntaxhighlight>-->
 
An uncaught exception terminates the program in error, otherwise control resumes in the catch clause or after the end try,
Line 2,300 ⟶ 2,337:
PHL does not support multiple catch-clauses.
 
<langsyntaxhighlight lang="phl">module exceptions;
 
extern printf;
Line 2,322 ⟶ 2,359:
}
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
Line 2,331 ⟶ 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,355 ⟶ 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,364 ⟶ 2,401:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
/* Define a new exception, called "my_condition". */
on condition (my_condition) snap begin;
Line 2,376 ⟶ 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,408 ⟶ 2,445:
raise;
end;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 2,414 ⟶ 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,429 ⟶ 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,446 ⟶ 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,459 ⟶ 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,472 ⟶ 2,509:
Write-Host "Other exception"
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,483 ⟶ 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,510 ⟶ 2,547:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">foo(X) :-
\+ integer(X),
throw(b('not even an int')).
Line 2,528 ⟶ 2,565:
format('~w~n', Msg),
!.
handle(X) :- throw(X).</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,549 ⟶ 2,586:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure ErrorHandler()
MessageRequester("Exception test", "The following error happened: " + ErrorMessage())
EndProcedure
Line 2,557 ⟶ 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,563 ⟶ 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,579 ⟶ 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,598 ⟶ 2,635:
try-except-else-finally
 
<langsyntaxhighlight lang="python">try:
foo()
except SillyError, se:
Line 2,607 ⟶ 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,614 ⟶ 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,623 ⟶ 2,660:
quux()
finally:
baz()</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 2,635 ⟶ 2,672:
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>.
 
<langsyntaxhighlight Quackerylang="quackery"> <flag on stack indicating if condition detected>
if [ $ "It all went pear shaped in 'a'." message put bail ]</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Quackerylang="quackery"> 3 backup a bailed if [ message take echo$ b ]</langsyntaxhighlight>
 
<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>.
Line 2,651 ⟶ 2,688:
 
'''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,676 ⟶ 2,713:
finally = message("This is called whether or not an exception occured")
)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,694 ⟶ 2,731:
;; raise the exception
(raise (exn:my-exception "Hi!" (current-continuation-marks))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,700 ⟶ 2,737:
{{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" perl6line>try {
die "Help I'm dieing!";
CATCH {
Line 2,716 ⟶ 2,753:
CATCH {
default { note "No you're not."; say $_.Str; }
}</langsyntaxhighlight>
 
<pre>
Line 2,728 ⟶ 2,765:
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" perl6line>sub f(){
ENTER { note '1) f has been entered' }
LEAVE { note '2) f has been left' }
Line 2,740 ⟶ 2,777:
CATCH {
when X::AdHoc { note q{6) no, I'm dead}; }
}</langsyntaxhighlight>
 
<pre>1) f has been entered
Line 2,749 ⟶ 2,786:
=={{header|Raven}}==
 
<langsyntaxhighlight lang="raven">42 as custom_error
 
define foo
Line 2,758 ⟶ 2,795:
catch
custom_error =
if 'oops' print</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,765 ⟶ 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,777 ⟶ 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,786 ⟶ 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,798 ⟶ 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,811 ⟶ 2,854:
'''Handling an exception'''
 
<langsyntaxhighlight lang="ruby">
# raise (throw) an exception
def spam
Line 2,822 ⟶ 2,865:
rescue SillyError => se
puts se # writes 'egg' to stdout
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">begin
foo
rescue ArgumentError => e
Line 2,838 ⟶ 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,844 ⟶ 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,853 ⟶ 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,859 ⟶ 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,869 ⟶ 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,919 ⟶ 2,962:
panicking_function();
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,929 ⟶ 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,990 ⟶ 3,033:
object NotImplementedErrorTest extends App {
??? // Throws scala.NotImplementedError: an implementation is missing
}</langsyntaxhighlight>
 
{{out}}Running entry point CheckingAccount
Line 3,011 ⟶ 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 3,032 ⟶ 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 3,049 ⟶ 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,069 ⟶ 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,075 ⟶ 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,099 ⟶ 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,120 ⟶ 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,132 ⟶ 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,158 ⟶ 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,190 ⟶ 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,210 ⟶ 3,252:
Example of usage:
 
<langsyntaxhighlight lang="stata">capture confirm file titanium.dta
if _rc {
if _rc==601 {
Line 3,219 ⟶ 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,227 ⟶ 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,244 ⟶ 3,286:
} catch {
//Catch any exception
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Throw
Line 3,261 ⟶ 3,303:
}
 
f</langsyntaxhighlight>
This creates the stack trace
<pre>error message for stack trace
Line 3,272 ⟶ 3,314:
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
mainModule : {
Line 3,296 ⟶ 3,338:
_start: (lambda (func1))
}
</syntaxhighlight>
</lang>
OUTPUT:
---------------
Line 3,318 ⟶ 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,339 ⟶ 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,355 ⟶ 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,370 ⟶ 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,387 ⟶ 3,429:
 
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|VBA}}==
Line 3,404 ⟶ 3,446:
 
'''Throw exceptions'''
<langsyntaxhighlight lang="vb">Sub foo1()
err.raise(vbObjectError + 1050)
End Sub
Line 3,411 ⟶ 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,459 ⟶ 3,501:
end_try:
'by convention, often just a drop through from the catch block
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
'''Defining exceptions'''
<langsyntaxhighlight lang="vbnet">Class MyException
Inherits Exception
'data with info about exception
End Class</langsyntaxhighlight>
 
'''Throw exceptions'''
<langsyntaxhighlight lang="vbnet">Sub foo()
Throw New MyException
End Sub</langsyntaxhighlight>
 
'''Catching exceptions'''
<langsyntaxhighlight lang="vbnet">Sub bar()
Try
foo()
Line 3,488 ⟶ 3,530:
'code here occurs whether or not there was an exception
End Try
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 3,496 ⟶ 3,538:
 
Here's an example of all this.
<langsyntaxhighlight ecmascriptlang="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.")
Line 3,513 ⟶ 3,555:
System.print("%(e[0]) / %(e[1]) = %(d)")
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,523 ⟶ 3,565:
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,535 ⟶ 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,545 ⟶ 3,623:
}
f(False); println("--------");
f(True);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,558 ⟶ 3,636:
 
=={{header|Zig}}==
<langsyntaxhighlight lang="zig">const std = @import("std");
// To replace exceptions, Zig has error enums to handle error states.
 
Line 3,576 ⟶ 3,654:
return err;
};
}</langsyntaxhighlight>
6

edits