Exceptions: Difference between revisions
Add page to "Flow control" category.
Langurmonkey (talk | contribs) |
Flexibeast (talk | contribs) (Add page to "Flow control" category.) |
||
(34 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}}==
<
String message
F (message)
Line 20 ⟶ 21:
X.try
X.throw SillyError(‘egg’)
X.catch SillyError se
print(se.message)</
=={{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
'''Raise an exception'''
<
begin
raise Foo_Error;
end Foo;</
Re-raising once caught exception:
<
exception
when Foo_Error =>
if ... then -- Alas, cannot handle it here,
raise; -- continue propagation of
end if;</
'''Handle an exception'''
<
begin
Foo;
Line 51 ⟶ 84:
when others =>
... -- this catches all other exceptions
end Call_Foo;</
'''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:
<
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;</
=={{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.
<
try {
var lines = readfile ("input.txt")
Line 81 ⟶ 114:
}
</syntaxhighlight>
'''Throwing exceptions'''<br>
You can throw any value.
<
if (error) {
throw "Error"
Line 95 ⟶ 128:
</syntaxhighlight>
=={{header|Aime}}==
'''Simple Exception Throwing'''
<
throwing(void)
{
Line 123 ⟶ 156:
return 0;
}</
{{out}}
<pre>ready to catch
Line 130 ⟶ 163:
caught!</pre>
'''Exception Types'''
<
ft(integer a, text &s)
{
Line 168 ⟶ 201:
return 0;
}</
{{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'''<
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</
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</
<pre>
sum sqs: +4900
Line 394 ⟶ 427:
'''try'''
<
set num to 1 / 0
--do something that might throw an error
end try</
'''try-on error'''
<
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</
'''error'''
<
=={{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
BadlyCodedFunc()
catch e
Line 422 ⟶ 470:
BadlyCodedFunc() {
throw Exception("Fail", -1)
}</
=== ErrorLevel-based exceptions ===
In [[AutoHotkey_Basic]], the only option for error-handling is using ErrorLevel
<syntaxhighlight lang="autohotkey">foo()
If ErrorLevel
Msgbox calling foo failed with: %ErrorLevel%
Line 436 ⟶ 484:
ErrorLevel = foo_error
Return
}</
=={{header|
==={{header|BBC BASIC}}===
<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</
'''Output:'''
<pre>
Line 457 ⟶ 506:
=={{header|blz}}==
<
try
1 / 0 # Throw an exception
Line 464 ⟶ 513:
print("An error occured!")
end
</syntaxhighlight>
=={{header|Bracmat}}==
Line 488 ⟶ 537:
percolates further up, so calling the function <code>MyFunction</code> fails as well, making the whole program fail.
<
= someText XMLstuff
. ( get$!arg:?someText
Line 504 ⟶ 553:
)
& MyFunction$"Tralula.txt"
);</
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'''
<
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
Line 544 ⟶ 608:
/* there is no way to "let the exception through" */
}
}</
With multi-thread support and nested exceptions
<syntaxhighlight lang="c">
#include <stdio.h>
#include <setjmp.h>
Line 631 ⟶ 695:
}
</syntaxhighlight>
Now all we need to do is add a finally block :) hint: it is possible
=={{header|C
{{works with|Visual Studio|2005}}
'''Defining exceptions'''
<
{
// data with info about exception
};</
'''Throw exceptions'''
<syntaxhighlight lang="csharp">void foo()
{
throw MyException();
}</syntaxhighlight>
'''Catching exceptions'''
<
foo();
}
catch (MyException
{
// handle exceptions of type MyException and derived
}
catch
{
// handle any type of exception not handled by above catches
}</
=={{header|C
In C++ an exception can be of any copyable type, this includes int's, other primitives, as well as objects.
'''Defining exceptions'''
<syntaxhighlight lang
{
// data with info about exception
};</
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'''
<
{
throw MyException();
}</
'''Catching exceptions'''
<
foo();
}
catch (MyException
{
// handle exceptions of type MyException and derived
}
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
}</
=={{header|Clojure}}==
Expression handling in Clojure is basically like Java in S-expressions:
<
(if (> (rand) 0.5)
(throw (RuntimeException. "oops!"))
Line 732 ⟶ 778:
(println e)
(finally
(println "always see this"))</
=={{header|ColdFusion}}==
Line 739 ⟶ 785:
inside <cfscript>:
<
foo();
} catch (Any e) {
// handle exception e
}</
otherwise:
<
<cfcatch type="Database|...">
</cfcatch>
</cftry></
=={{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.
<
((number :reader number :initarg :number))
(:report (lambda (condition stream)
Line 768 ⟶ 814:
(handler-case (get-number)
(unexpected-odd-number (condition)
(1+ (number condition)))))</
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}}==
<
/// Throw Exceptions
Line 809 ⟶ 855:
void main() {
test4();
}</
=={{header|Delphi}}==
'''Throw Exceptions'''
<
begin
raise Exception.Create('Sample Exception');
end;</
'''Catch Exceptions'''
<
begin
try
Line 828 ⟶ 874:
raise; // Rethrowing
end;
end;</
'''Ways to implement finally'''
<
begin
try
Line 838 ⟶ 884:
ShowMessage('test3 finally');
end;
end;</
=={{header|
<syntaxhighlight lang="dyalect">func Integer.Add(x) {
throw @NegativesNotAllowed(x) when x < 0
this + x
}
try {
12.Add(-5)
} catch {
@NegativesNotAllowed(x) => print("Negative number: \(x)")
}</syntaxhighlight>
=={{header|DWScript}}==
'''Throw Exceptions'''
<
begin
raise Exception.Create('Sample Exception');
end;</
'''Catch Exceptions'''
<
begin
try
Line 871 ⟶ 918:
end;
end;
end;</
'''Ways to implement finally'''
<
begin
try
Line 881 ⟶ 928:
PrintLn('Test3 finally');
end;
end;</
=={{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.
<
if (arg == 43) {
return "Bob"
Line 913 ⟶ 972:
return ["notok", exceptionObj]
}
}</
<
# 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]</
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:
<
if (arg == 43) {
return "Bob"
Line 948 ⟶ 1,007:
return ["notok", exceptionObj]
}
}</
<
# value: ["not ok", problem: Who?]
Line 957 ⟶ 1,016:
? catching(45.7)
# problem: the float64 45.7 doesn't coerce to an int</
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:
<
def nameOf(arg :int, ejector) {
if (nameTable == null) {
Line 977 ⟶ 1,036:
ejector(makeNotFoundException("Who?"))
}
}</
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'''
<
{
constructor new()
<= super new("MyException raised");
}</
'''Throw exceptions'''
<
{
MyException
}
</syntaxhighlight>
'''Catching exceptions'''
<
{
}
catch
{
// handle exceptions of type MyException and derived
}</
'''Catching any exception'''
<syntaxhighlight lang
{
foo.fail()
}
catch(Exception e)
{
// handle any type of exception
};</
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( exceptions ).
Line 1,027 ⟶ 1,090:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,037 ⟶ 1,100:
'''Throw Exceptions'''
<
TUPLE: velociraptor ;
\ velociraptor new throw</
Or a shorthand for this:
<
velociraptor</
'''Catch Exceptions'''
<
: 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</
=={{header|Fancy}}==
<
# 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
}</
=={{header|Fantom}}==
<
// Create a new error class by subclassing sys::Err
const class SpecialErr : Err
Line 1,108 ⟶ 1,171:
}
}
</syntaxhighlight>
{{out}}
Line 1,120 ⟶ 1,183:
'''Throw Exceptions'''
<
: g ( -- ) 0 throw ." g " ; \ does not throw</
'''Catch Exceptions'''
<
: test ( -- )
['] f catch report
['] g catch report ;</
test example. (Output shown in bold)
<
'''caught 1 g no throw ok'''</
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:
<
=={{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:
<
Enum ErrorType
Line 1,167 ⟶ 1,230:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,176 ⟶ 1,239:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c3abec93bc7f135203f1f7582f5c3a19 Click this link to run this code]'''
<
Dim iInteger As Integer
Line 1,205 ⟶ 1,268:
Print Error.Text
End</
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).
<
import "fmt"
Line 1,241 ⟶ 1,304:
foo()
fmt.Println("glad that's over.")
}</
{{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:
<
throwIO SomeException</
In purely functional context, use "throw" to throw exceptions; the expression will match any type:
<
else throw SomeException</
To throw a user-defined exception, use "throwDyn":
<
else throwDyn myException</
'''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:
<
{- do IO computations here -}
`catch` \ex -> do
{- handle exception "ex" here -}</
Note: Control.Exception's "catch" is different than Prelude's "catch".
To catch a user-defined exception, use "catchDyn":
<
{- do IO computations here -}
`catchDyn` \ex -> do
{- handle exception "ex" here -}</
=={{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.
<
U8 *err = 'Error';
throw(err); // throw exception
Line 1,296 ⟶ 1,359:
Print("Raised 'Error'");
PutExcept; // print the exception and stack trace
}</
==Icon and {{header|Unicon}}==
Line 1,306 ⟶ 1,369:
support exceptions.</i>
<
procedure main(A)
Line 1,322 ⟶ 1,385:
if numeric(i) = 3 then Exception().throw("bad value of "||i)
return i
end</
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.
<
if. y-:'bad argument' do.
throw.
Line 1,365 ⟶ 1,428:
tryThis 'bad argument'
Uh oh!</
=={{header|Java}}==
Line 1,371 ⟶ 1,434:
'''Defining exceptions'''
<
public class MyException extends Exception {
//Put specific info in here
Line 1,377 ⟶ 1,440:
//Unchecked exception
public class MyRuntimeException extends RuntimeException {}</
'''Throw exceptions'''
<
throw new MyException();
}
Line 1,386 ⟶ 1,449:
public void fooUnchecked() {
throw new MyRuntimeException();
}</
'''Catching exceptions'''
<
fooChecked();
}
Line 1,403 ⟶ 1,466:
finally {
//This code is always executed after exiting the try block
}</
{{works with|Java|7+}}
Java 7 added "multicatch" and "smart rethrow".
<
try{
throwsNumberFormatException();
Line 1,418 ⟶ 1,481:
throw e;
}
}</
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'''
<
throw new Error('Not implemented!');
}</
'''Catching exceptions'''
<
element.attachEvent('onclick', doStuff);
}
Line 1,441 ⟶ 1,504:
finally {
eventSetup = true;
}</
=={{header|jq}}==
{{works with|jq|>1.4}}
Line 1,450 ⟶ 1,514:
The "try" clause takes the form:
<syntaxhighlight lang
where FILTER and CATCHER may be any jq expressions.
Line 1,456 ⟶ 1,520:
'''Example''':
<
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;</
# test(0;0) # produces 0
Line 1,478 ⟶ 1,542:
{{works with|Julia|0.6}}
<
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</
=={{header|Kotlin}}==
<
// 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()
}</
{{out}}
Line 1,531 ⟶ 1,595:
=={{header|langur}}==
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.
<syntaxhighlight lang="langur">throw "not a math exception"
catch
if .e
# change result...
} else {
Line 1,547 ⟶ 1,610:
} else {
# no exception
}
</syntaxhighlight>
An else section on a catch is optional.
===
An exception variable may be specified, or you can simply use the implicit variable, which is _err.
<syntaxhighlight lang="langur">100 / 0
catch {
if _err'cat == "math" {
# change result
# rethrow the exception
throw
}
}
</syntaxhighlight>
<
.safediv(7, 7) # 1
.safediv(7, 0) # 0
</syntaxhighlight>
=={{header|Lasso}}==
<
handle_error => {
// do something else
}
fail(-1,'Oops')
}</
=={{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:
<
on alertHook (me, errorType, errorMessage, alertType)
Line 1,599 ⟶ 1,665:
return 1 -- continues movie playback, no error dialog
end</
<
on prepareMovie
_player.alertHook = script("ErrorHandler")
end</
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:
<
-- usage: throw("Custom error 23")
on throw (msg)
_player.alertHook.alertHook("Script runtime error", msg, #script)
abort() -- exits call stack
end</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
if :b = 0 [(throw "divzero 0)]
output :a / :b
Line 1,623 ⟶ 1,689:
to div.safely :a :b
output catch "divzero [div.checked :a :b]
end</
There are also some predefined exceptions:
* '''throw "toplevel''' returns to the interactive prompt if uncaught (like control-C)
Line 1,632 ⟶ 1,698:
=={{header|Logtalk}}==
Logtalk exception-handling mechanism is based on the catch/3 and throw/1 predicates inherited from Prolog:
<
:- object(exceptions).
Line 1,656 ⟶ 1,722:
:- end_object.
</syntaxhighlight>
{{out}}
<pre>
Line 1,673 ⟶ 1,739:
=={{header|Lua}}==
'''Throwing an Exception'''<br>
<syntaxhighlight lang="lua">
error("Something bad happened!")
</syntaxhighlight>
'''Catching Exceptions'''<br>
<syntaxhighlight lang="lua">
function throw_error()
error("Whoops")
Line 1,690 ⟶ 1,756:
status, errmsg = pcall(throw_error)
print("errmsg = ", errmsg)
</syntaxhighlight>
Note that `pcall` passes every argument after the function object or function name to said function:<br />
<syntaxhighlight lang="lua">
function throw_error_with_argment(argument)
error(string.format("Whoops! argument = %s", argument))
Line 1,702 ⟶ 1,768:
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)
</syntaxhighlight>
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">
function throw_error_with_argment(argument)
return "hello!"
Line 1,712 ⟶ 1,778:
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Errors {
Module Check {
Line 1,737 ⟶ 1,804:
Errors
Print Error$=""
</syntaxhighlight>
{{out}}
<pre>
Line 1,752 ⟶ 1,819:
fail.mk
<
false</
Using -@ to ignore the exception.
Line 1,759 ⟶ 1,826:
catch.mk
<
-@make -f fail.mk</
Using explicit exit 0 to ignore the exception.
Line 1,766 ⟶ 1,833:
catch.mk
<
make -f fail.mk; exit 0</
=={{header|Maple}}==
<syntaxhighlight lang="maple">
errorproc:=proc(n)
local a;
Line 1,779 ⟶ 1,846:
end try;
end proc;
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Example usage :
Line 1,789 ⟶ 1,856:
Catch[f[2] + f[3]]
-> 8</
=={{header|MATLAB}}==
Line 1,795 ⟶ 1,862:
Sample usage:
<
??? Help</
=={{header|Modula-3}}==
Line 1,802 ⟶ 1,869:
'''Defining exceptions'''<br>
Exceptions can only be declared at the "top-level" of a module or interface. Arguments are optional.
<
EXCEPTION Error(TEXT);</
'''Throw exceptions'''<br>
Exceptions can be bound to procedures using RAISES:
<
...
RAISE EndOfFile;
...</
'''Catching exceptions'''
<
Foo();
EXCEPT
| EndOfFile => HandleFoo();
END;</
Modula-3 also has a FINALLY keyword:
<
Foo();
FINALLY
CleanupFoo(); (* always executed *)
END;</
=={{header|MOO}}==
Line 1,831 ⟶ 1,897:
'''Throw exceptions'''<br>
Values can be raised to exceptions using raise():
<syntaxhighlight lang
'''Catching exceptions'''
<
this:foo();
except e (ANY)
this:bar(e);
endtry</
MOO also has a finally statement:
<
this:foo();
finally
this:bar();
endtry</
'''Shorthand'''
<
=={{header|Nanoquery}}==
<
invalid "this statement will fail"
catch e
println "caught an exception"
println e
end try</
Throwing exceptions:
<
=={{header|Nemerle}}==
<
class MyException : Exception
{
Line 1,883 ⟶ 1,949:
finally {
... // code executes whether or not exception was thrown
}</
=={{header|NetRexx}}==
As <tt>NetRexx</tt> runs under the control of a JVM it has the same exception model as [[#Java|Java]].
<
options replace format comments java crossref symbols nobinary
Line 1,915 ⟶ 1,981:
super('I resent that!')
return
</syntaxhighlight>
'''Output:'''
<pre>
Line 1,923 ⟶ 1,989:
=={{header|Nim}}==
'''Defining exceptions'''
<
'''Throwing an exception'''
<
raise newException(SillyError, "Some error")</
'''Handling an exception'''
<
spam()
except SillyError:
Line 1,935 ⟶ 2,001:
echo "Got another exception"
finally:
echo "Finally"</
=={{header|Objective-C}}==
Line 1,941 ⟶ 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:
<
//Put specific info in here
}
@end</
'''Throw exceptions'''
<
@throw [NSException exceptionWithName:@"TerribleException"
reason:@"OMGWTFBBQ111!1" userInfo:nil];
}</
'''Catching exceptions'''
<
[self foo];
}
Line 1,968 ⟶ 2,034:
@finally {
//This code is always executed after exiting the try block
}</
=={{header|OCaml}}==
Line 1,974 ⟶ 2,040:
'''Defining exceptions'''<br>
Like constructors, exceptions may or may not have an argument:
<
exception Another_Exception of string;;</
'''Throw exceptions'''<br>
Throw exceptions with the "raise" function; the expression will match any type:
<
match x with
1 -> raise My_Exception
| 2 -> raise (Another_Exception "hi mom")
| _ -> 5
;;</
'''Catching exceptions'''<br>
The "with" syntax pattern-matches on the exception type and argument:
<
string_of_int (foo 2)
with
My_Exception -> "got my exception"
| Another_Exception s -> s
| _ -> "unknown exception"</
=={{header|Oforth}}==
Line 2,002 ⟶ 2,067:
It is also possible to create new exception classes (see Exception.of).
<
: iwillCatch
Line 2,008 ⟶ 2,073:
try: e [ iwillThrowAnException ] when: [ "Exception catched :" . e .cr ]
try: e [ 1 2 over last ] when: [ "Exception catched :" . e .cr ]
"Done" println ;</
{{out}}
Line 2,021 ⟶ 2,086:
'''Throw exceptions'''<br>
Any value can be thrown as an exception. Typically record values are used.
<
raise slightlyLessSilly(data:42 reason:outOfMemory) end</
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).
<
raise someError(debug:unit) end
catch someError(debug:d(stack:ST ...)...) then
{Inspect ST}
end</
See also: [http://www.mozart-oz.org/documentation/base/exception.html Exceptions] in the Oz documentation.
Line 2,036 ⟶ 2,101:
'''Catching exceptions'''<br>
Exception are caught with pattern matching. Ellipsis indicating additional optional fields are often useful here.
<
{Foo}
catch sillyError then
Line 2,046 ⟶ 2,111:
finally
{Fin}
end</
=={{header|PARI/GP}}==
Line 2,077 ⟶ 2,142:
|User-initiated error
|}
<
"caught"
,
error("bad stuff")
)</
===Throwing errors in GP===
The only error that can be thrown in GP is user error:
<
===Throwing errors in PARI===
Line 2,188 ⟶ 2,253:
|}
</div>
<
===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:
<
if (x == (GEN)1L) // Was there an error?
pari_printf("Don't do that!\n"); // Recover</
=={{header|Pascal}}==
Line 2,204 ⟶ 2,269:
Exceptions using the core [http://perldoc.perl.org/functions/eval.html eval] function:
<
die "Danger, danger, Will Robinson!";
Line 2,214 ⟶ 2,279:
# rethrow
die $@;</
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,221 ⟶ 2,286:
The same using the [http://search.cpan.org/perldoc?Try::Tiny Try::Tiny] module:
<
die "Danger, danger, Will Robinson!";</
<
try {
die "this could go wrong mightily";
} catch {
print;
};</
<
die $_;</
'''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|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">-->
<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;">)
<!--</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">-->
<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>
<span style="color: #008080;">catch</span> <span style="color: #000000;">e</span>
<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>
<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>
<span style="color: #008080;">else</span>
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">e<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">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
=={{header|PHL}}==
Line 2,316 ⟶ 2,337:
PHL does not support multiple catch-clauses.
<
extern printf;
Line 2,338 ⟶ 2,359:
}
return 0;
]</
=={{header|PHP}}==
Line 2,347 ⟶ 2,368:
'''Define exceptions'''
<
{
// Custom exception attributes & methods
}</
'''Throwing exceptions'''
<
{
throw new Exception('Exception message');
}</
'''Catching Exceptions'''
<
throwsException();
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}</
=={{header|PicoLisp}}==
Line 2,371 ⟶ 2,392:
'throw' will transfer control to a 'catch' environment
that was set up with the given label.
<
(println 1) # Do some processing (print '1')
(throw 'thisLabel 2) # Abort processing and return '2'
(println 3) ) # This is never reached</
{{out}}
<pre>1 # '1' is printed
Line 2,380 ⟶ 2,401:
=={{header|PL/I}}==
<syntaxhighlight lang="text">
/* Define a new exception, called "my_condition". */
on condition (my_condition) snap begin;
Line 2,392 ⟶ 2,413:
/* to be printed, and execution then resumes at the statement */
/* following the SIGNAL statement. */
</syntaxhighlight>
=={{header|PL/pgSQL}}==
'''Raise an exception'''
<syntaxhighlight lang="sql">
begin
raise exception 'this is a generic user exception';
raise exception division_by_zero;
end;
</syntaxhighlight>
'''Handle an exception'''
Hande division by zero and re-raising once caught other exception:
<syntaxhighlight lang="sql">
create function special_division(p_num double precision, p_den double precision) returns text
as $body$
Line 2,424 ⟶ 2,445:
raise;
end;
</syntaxhighlight>
=={{header|Pop11}}==
Line 2,430 ⟶ 2,451:
'''Throwing exceptions'''
<
throw([my_exception my_data]);
enddefine;</
'''Catching exceptions'''
<
vars cargo;
define catcher();
Line 2,445 ⟶ 2,466:
enddefine;
main();</
=={{header|PowerShell}}==
'''Throw an exception:'''
<syntaxhighlight lang="powershell">
throw "Any error message."
</syntaxhighlight>
{{Out}}
<pre>
Line 2,462 ⟶ 2,483:
</pre>
'''Throw a more specific exception:'''
<syntaxhighlight lang="powershell">
throw [System.IO.FileNotFoundException] ".\temp.txt not found."
</syntaxhighlight>
{{Out}}
<pre>
Line 2,475 ⟶ 2,496:
</pre>
'''Using <code>try {} catch {}</code> is better for more complex error checking because you can test specific errors:'''
<syntaxhighlight lang="powershell">
try
{
Line 2,488 ⟶ 2,509:
Write-Host "Other exception"
}
</syntaxhighlight>
{{Out}}
<pre>
Line 2,499 ⟶ 2,520:
</pre>
'''Errors are objects like any other in PowerShell, so you may capture any detail of it:'''
<syntaxhighlight lang="powershell">
$Error[0] | Get-Member
</syntaxhighlight>
{{Out}}
<pre>
Line 2,526 ⟶ 2,547:
=={{header|Prolog}}==
<
\+ integer(X),
throw(b('not even an int')).
Line 2,544 ⟶ 2,565:
format('~w~n', Msg),
!.
handle(X) :- throw(X).</
{{Out}}
<pre>
Line 2,565 ⟶ 2,586:
=={{header|PureBasic}}==
<
MessageRequester("Exception test", "The following error happened: " + ErrorMessage())
EndProcedure
Line 2,573 ⟶ 2,594:
OnErrorCall(@ErrorHandler())
RaiseError(#PB_OnError_InvalidMemory) ;a custom error# can also be used here depending on the OS being compiled for</
=={{header|Python}}==
Line 2,579 ⟶ 2,600:
'''Defining an exception'''
<
class SillyError(exceptions.Exception):
def __init__(self,args=None):
self.args=args</
Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:
<
pass</
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,595 ⟶ 2,616:
Creating an exception using the default constructor of an exception class:
<
raise SillyError # equivalent to raise SillyError()</
{{works with|Python|2.5}}
Passing an argument to the constructor of an exception class:
<
raise SillyError, 'egg' # equivalent to raise SillyError('egg')</
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}}
<
raise SillyError('egg')</
'''Handling an exception'''<br>
Line 2,614 ⟶ 2,635:
try-except-else-finally
<
foo()
except SillyError, se:
Line 2,623 ⟶ 2,644:
quux()
finally:
baz()</
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,630 ⟶ 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''
<
foo()
except SillyError as se:
Line 2,639 ⟶ 2,660:
quux()
finally:
baz()</
=={{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">
e <- simpleError("This is a simpleError")
</syntaxhighlight>
'''Raise an exception'''
<syntaxhighlight lang="r">
stop("An error has occured")
stop(e) #where e is a simpleError, as above
</syntaxhighlight>
'''Handle an exception'''
<syntaxhighlight lang="r">
tryCatch(
{
Line 2,669 ⟶ 2,713:
finally = message("This is called whether or not an exception occured")
)
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
Line 2,687 ⟶ 2,731:
;; raise the exception
(raise (exn:my-exception "Hi!" (current-continuation-marks))))
</syntaxhighlight>
=={{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}}==
<
define foo
Line 2,700 ⟶ 2,795:
catch
custom_error =
if 'oops' print</
=={{header|REXX}}==
Line 2,707 ⟶ 2,802:
This type of exception handling (in REXX) has its limitation
(the label is local to the program, not external subroutines).
<
do j=9 by -5
say 'the square root of ' j " is " sqrt(j)
Line 2,719 ⟶ 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</
'''output'''
<pre>
Line 2,728 ⟶ 2,823:
=={{header|Ring}}==
<
Try
see 1/0
Catch
raise("Sorry we can't divide 1/0" + nl)
Done
</syntaxhighlight>
=={{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,740 ⟶ 2,841:
'''Defining an exception'''
<
class SillyError < Exception
end</
SillyError is simply declared as a subclass of Exception. No over-riding is necessary.
<
end</
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,753 ⟶ 2,854:
'''Handling an exception'''
<
# raise (throw) an exception
def spam
Line 2,764 ⟶ 2,865:
rescue SillyError => se
puts se # writes 'egg' to stdout
end</
<
foo
rescue ArgumentError => e
Line 2,780 ⟶ 2,881:
# always runs
baz
end</
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,786 ⟶ 2,887:
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages.
<
quotient = 1 / 0 rescue "sorry"</
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,795 ⟶ 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.
<
throw :done
end
Line 2,801 ⟶ 2,902:
catch :done do
foo
end</
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,811 ⟶ 2,912:
It is illustrated by the code below:
<
// Error
use std::io::{Error, ErrorKind};
Line 2,861 ⟶ 2,962:
panicking_function();
}
}</
=={{header|Scala}}==
Line 2,871 ⟶ 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.
<
class AccountBlockException extends Exception
class InsufficientFundsException(val amount: Double) extends Exception
Line 2,932 ⟶ 3,033:
object NotImplementedErrorTest extends App {
??? // Throws scala.NotImplementedError: an implementation is missing
}</
{{out}}Running entry point CheckingAccount
Line 2,953 ⟶ 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).<
(if (even? xx)
xx
Line 2,974 ⟶ 3,075:
(all-ok)))
(display "oh my god it is ODD!")))</
=={{header|Seed7}}==
'''Raise an exception'''<
begin
raise RANGE_ERROR;
end func;</
'''Handle an exception'''
<
begin
block
Line 2,991 ⟶ 3,092:
writeln("catched RANGE_ERROR");
end block;
end func;</
=={{header|Sidef}}==
An exception is thrown by the ''die'' keyword, which, if not caught, it terminates the program with an appropriate exit code.
<
die "I'm dead!"
}
catch { |msg|
say "msg: #{msg}" # msg: I'm dead! at test.sf line 2.
}
say "I'm alive..."
die "Now I'm dead!"
say "Or am I?"
{{out}}
<pre>
Line 3,011 ⟶ 3,111:
msg: I'm dead! at test.sf line 2.
I'm alive...
Now I'm dead! at test.sf line
</pre>
Line 3,017 ⟶ 3,117:
'''Handling Exceptions'''
<
[
block handlingCases: {Abort -> [| :_ | ^ Nil]}
].</
'''Define Exceptions'''
<
"An Abort is a Restart which exits the computation, unwinding the stack."
Line 3,041 ⟶ 3,141:
[
c tryHandlers
].</
'''Throwing Exceptions'''<br>
{{lines too long|Slate}}
<
=={{header|Smalltalk}}==
Throwing an Exception
<
"exit"
Transcript show: 'Throwing yawp'; cr.
self error: 'Yawp!'.</
<
Throwing yawp
Object: nil error: Yawp!
Line 3,062 ⟶ 3,162:
Error(Exception)>>signal: (AnsiExcept.st:226)
UndefinedObject(Object)>>error: (AnsiExcept.st:1565)
UndefinedObject>>executeStatements (yawp.st:5)</
Handling an Exception
<
"exit"
Line 3,074 ⟶ 3,174:
] on: Error do: [ :e |
Transcript show: 'Caught yawp'; cr.
].</
<
Throwing yawp
Caught yawp</
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL PL:
<
--#SET TERMINATOR @
Line 3,100 ⟶ 3,200:
END IF;
END @
</syntaxhighlight>
The next example just raise an exception, does not wrap a raised one.
<
BEGIN
SIGNAL SQLSTATE '75002'
SET MESSAGE_TEXT = 'Customer number is not known';
END @
</syntaxhighlight>
Output:
<pre>
Line 3,132 ⟶ 3,232:
'''Define Exceptions'''
<
exception MyDataException of int; (* can be any first-class type, not just int *)</
'''Throw Exceptions'''
<
fun g() = raise MyDataException 22;</
'''Catch Exceptions'''
<
val y = f() handle MyDataException x => x;</
=={{header|Stata}}==
Line 3,152 ⟶ 3,252:
Example of usage:
<
if _rc {
if _rc==601 {
Line 3,161 ⟶ 3,261:
display "there was an error with return code " _rc
}
}</
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,169 ⟶ 3,269:
'''Defining exceptions'''<br />
Exceptions can be of any type that conforms to the <code>ErrorType</code> protocol.
<
case TerribleException
}</
'''Throw exceptions'''<br />
A function that throws an exception must be explicitly declared so:
<
throw MyException.TerribleException
}</
'''Catching exceptions'''
<
try foo()
} catch MyException.TerribleException { // this can be any pattern
Line 3,186 ⟶ 3,286:
} catch {
//Catch any exception
}</
=={{header|Tcl}}==
<
# Throw
Line 3,203 ⟶ 3,303:
}
f</
This creates the stack trace
<pre>error message for stack trace
Line 3,212 ⟶ 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,223 ⟶ 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.
<
@(defex monkey primate)
@(defex human primate)
Line 3,244 ⟶ 3,381:
@(end)@#output
@(end)@#try
@(end)@#collect</
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,260 ⟶ 3,397:
=={{header|Ursa}}==
Catching exceptions:
<
invalid "this statement will fail"
catch syntaxerror
# console.err is optional here
out "caught an exception" endl console.err
end try</
Throwing exceptions:
<
=={{header|Ursala}}==
Line 3,275 ⟶ 3,412:
raises an exception with the diagnostic message 'epic fail'.
(The diagnostic message can also be made to depend on the input.)
<
thrower = ~&?/'success'! -[epic fail]-!%
catcher = guard(thrower,---[someone failed]-)</
If the exception is not caught, the program terminates immediately and
Line 3,288 ⟶ 3,425:
In this example, the exception handler appends some additional
verbiage to the message.
=={{header|V}}==
throwing exceptions
<
['new error' 1 2 3] throw
'should not come here' puts
].</
catching them
<
=[new error 1 2 3]</
=={{header|VBA}}==
Line 3,337 ⟶ 3,446:
'''Throw exceptions'''
<
err.raise(vbObjectError + 1050)
End Sub
Line 3,344 ⟶ 3,453:
Error vbObjectError + 1051
End Sub
</syntaxhighlight>
'''Catching exceptions'''
<
'by convention, a simple handler
On Error GoTo catch
Line 3,392 ⟶ 3,501:
end_try:
'by convention, often just a drop through from the catch block
End Sub</
=={{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}}==
<
catch { println(__exception," was thrown") }
fallthrough { println("No exception was thrown") }
println("OK");</
{{out}}
<pre>
Line 3,405 ⟶ 3,613:
</pre>
If you want "finally" functionality, use onExit or onExitBlock:
<
try{
onExitBlock("Exit code".println);
Line 3,415 ⟶ 3,623:
}
f(False); println("--------");
f(True);</
{{out}}
<pre>
Line 3,426 ⟶ 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>
|