Exceptions/Catch an exception thrown in a nested call: Difference between revisions

 
(68 intermediate revisions by 29 users not shown)
Line 1:
{{Task|Control Structures}}
{{omit from|C}}
{{omit from|GUISS}}
{{omit from|M4}}
{{omit from|Retro}}
{{omit from|Swift}}
 
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.
Line 17 ⟶ 15:
Show/describe what happens when the program is run.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">T U0 {}
T U1 {}
 
F baz(i)
I i == 0
X.throw U0()
E
X.throw U1()
 
F bar(i)
baz(i)
 
F foo()
L(i) 0..1
X.try
bar(i)
X.catch U0
print(‘Function foo caught exception U0’)
 
foo()</syntaxhighlight>
 
{{out}}
<pre>
Function foo caught exception U0
</pre>
The exact [http://rosettacode.org/wiki/Talk:Exceptions/Catch_an_exception_thrown_in_a_nested_call#11l_swallows_U1.3F behavior] for an uncaught exception is implementation-defined [as in C++].
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Exceptions_From_Nested_Calls is
Line 49 ⟶ 76:
Foo;
end loop;
end Exceptions_From_Nested_Calls;</langsyntaxhighlight>
{{out}}
<pre>
Line 61 ⟶ 88:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
baz(integer i)
{
Line 101 ⟶ 128:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Exception `U0' thrown
Line 110 ⟶ 137:
 
=={{header|ALGOL 68}}==
{{trans|pythonPython}}
 
{{works with|ALGOL 68|Standard - no extensions to language used}}
Line 122 ⟶ 149:
 
c.f. [[Exceptions#ALGOL_68|ALGOL 68 Exceptions]] for more details.
<langsyntaxhighlight lang="algol68">MODE OBJ = STRUCT(
INT value,
STRUCT(
Line 177 ⟶ 204:
FI;
 
foo</langsyntaxhighlight>
{{out}}
<pre>
Line 191 ⟶ 218:
'''par''' clause, then all parallel the threads are terminated and the
program continues in the parent thread. <!-- example needed -->
 
=={{header|Amazing Hopper}}==
<p>Hopper has a basic "try/catch" handling, and must be handled manually. Only one exception will be raised.</p>
<p>VERSION 1: </p>
<syntaxhighlight lang="c">
#include <jambo.h>
 
Main
e=0, se=""
Try
Gosub 'Foo'
Catch (e)
Get msg exception, and Move to 'se'
Printnl ("+-MAIN-FOO CALL Error: ",e, " : ", se )
Finish
End
 
Subrutines
 
Define ' Foo '
Gosub ' Bar '
Return
 
Define ' Bar '
Set '0', Gosub ' Biz '
Set '1', Gosub ' Biz '
Return
 
Define ' Biz, x '
a=0, b=0
If ( x )
Let ' b:=Sqrt(-1) '
Nan( a ) do{ Raise (1000,"\n+----Func BIZ: NaN!") }
Else
#( a=log(-1) + log(-1) )
Nan( a ) do{ Raise (1001,"\n+----Func BIZ: NaN!") }
End If
Printnl ' "a = ", a, " b = ", b '
 
Return
</syntaxhighlight>
{{out}}
<pre>
+-MAIN-FOO CALL Error: 1001 :
+----Func BIZ: NaN!
</pre>
<p>VERSION 2: </p>
<syntaxhighlight lang="c">
#include <jambo.h>
 
Main
e=0, se=""
Try
Gosub 'Foo'
Catch (e)
Get msg exception, and Move to 'se'
Printnl ("+-MAIN Error: ",e, " : ", se )
Finish
End
 
Subrutines
 
/*
This "Try" is not considered nested, then, it is necessary
to capture the error and raise the error
*/
Define ' Foo '
Try
Gosub ' Bar '
Catch (e)
Get msg exception, and Move to 'se'
Free try // absolutly nessesary in this chase!
Raise (e, Cat ("\n+--FUNC FOO: ", se) )
Finish
Return
 
Define ' Bar '
Try
Set '0', Gosub ' Biz '
Set '1', Gosub ' Biz '
Catch(e)
Get msg exception, and Move to 'se'
Free try // absolutly nessesary in this chase!
Raise (e, Cat ("\n+---FUNC BAR: ", se) )
Finish
 
Return
 
Define ' Biz, x '
a=0, b=0
If ( x )
Let ' b:=Sqrt(-1) '
Nan( a ) do{ Raise (1000,"\n+----Func BIZ: NaN!") }
Else
#( a=log(-1) + log(-1) )
Nan( a ) do{ Raise (1001,"\n+----Func BIZ: NaN!") }
End If
Printnl ' "a = ", a, " b = ", b '
 
Return
</syntaxhighlight>
{{out}}
<pre>
+-MAIN Error: 1001 :
+--FUNC FOO:
+---FUNC BAR:
+----Func BIZ: NaN!
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="apl">:Namespace Traps
⍝ Traps (exceptions) are just numbers
⍝ 500-999 are reserved for the user
U0 U1←900 901
⍝ Catch
∇foo;i
:For i :In ⍳2
:Trap U0
bar i
:Else
⎕←'foo caught U0'
:EndTrap
:EndFor
⍝ Throw
∇bar i
⎕SIGNAL U0 U1[i]
:EndNamespace</syntaxhighlight>
 
{{out}}
 
<pre> Traps.foo
foo caught U0
ERROR 901
foo[3] bar i
</pre>
 
 
=={{header|AutoHotkey}}==
=== True exceptions ===
Line 197 ⟶ 370:
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/>
When this program is run, the first exception (U0) is raised, and caught by the try-catch section. This causes a Message Box containing the text "An exception was raised: First Exception" to be displayed by the script. The second exception is not caught, generating a runtime error.
<langsyntaxhighlight AHKlang="ahk">global U0 := Exception("First Exception")
global U1 := Exception("Second Exception")
 
Line 220 ⟶ 393:
else if ( calls = 2 )
throw U1
}</langsyntaxhighlight>
The runtime error:
<pre>Error: Second Exception
Line 242 ⟶ 415:
The global ErrorLevel keeps track of the last error.
Here is one way to keep track of nested errors:
<syntaxhighlight lang="autohotkey">foo()
<lang AutoHotkey>foo()
Return
 
Line 271 ⟶ 444:
ErrorLevel .= "U0"
Return 1
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM Allocate error numbers:
U0& = 123
U1& = 124
Line 301 ⟶ 474:
ENDCASE
ENDPROC
</syntaxhighlight>
</lang>
{{out}} (the second message is output by the default error handler):
<pre>Exception U0 caught in foo
Line 324 ⟶ 497:
U0 and U1 are boring for debugging purposes. Added something to help with that.
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 445 ⟶ 618:
 
 
</syntaxhighlight>
</lang>
{{out}}
<pre>Foo entering bar.
Line 457 ⟶ 630:
*** Error: U1 Bartender Error. Bartender kicked customer out of bar Baz.
</pre>
 
=={{header|C++}}==
First exception will be caught and message will be displayed,
second will be caught by the default exception handler,
which as required by the C++ Standard, will call terminate(),
aborting the task, typically with an error message.
 
<lang cpp>#include <iostream>
class U0 {};
class U1 {};
void baz(int i)
{
if (!i) throw U0();
else throw U1();
}
void bar(int i) { baz(i); }
void foo()
{
for (int i = 0; i < 2; i++)
{
try {
bar(i);
} catch(U0 e) {
std::cout<< "Exception U0 caught\n";
}
}
}
int main() {
foo();
std::cout<< "Should never get here!\n";
return 0;
}</lang>
 
Result:
<pre>
Exception U0 caught
This application has requested the Runtime to terminate it in an unusual way.
</pre>
The exact behavior for an uncaught exception is implementation-defined.
 
=={{header|C sharp|C#}}==
This example will first catch U0 and print "U0 Caught" to the console when it does. The uncaught U1 exception will then cause the program to terminate and print the type of the exception, location of the error, and the stack.
 
<langsyntaxhighlight lang="csharp">using System; //Used for Exception and Console classes
class Exceptions
{
Line 534 ⟶ 665:
foo();
}
}</langsyntaxhighlight>
 
{{out}}
Line 546 ⟶ 677:
</pre>
 
=={{header|C++}}==
First exception will be caught and message will be displayed,
second will be caught by the default exception handler,
which as required by the C++ Standard, will call terminate(),
aborting the task, typically with an error message.
 
<syntaxhighlight lang="cpp">#include <iostream>
class U0 {};
class U1 {};
void baz(int i)
{
if (!i) throw U0();
else throw U1();
}
void bar(int i) { baz(i); }
void foo()
{
for (int i = 0; i < 2; i++)
{
try {
bar(i);
} catch(U0 e) {
std::cout<< "Exception U0 caught\n";
}
}
}
int main() {
foo();
std::cout<< "Should never get here!\n";
return 0;
}</syntaxhighlight>
 
Result:
<pre>
Exception U0 caught
This application has requested the Runtime to terminate it in an unusual way.
</pre>
The exact behavior for an uncaught exception is implementation-defined.
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(def U0 (ex-info "U0" {}))
(def U1 (ex-info "U1" {}))
 
Line 564 ⟶ 736:
 
(defn -main [& args]
(foo))</langsyntaxhighlight>
 
{{output}}
Line 584 ⟶ 756:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(define-condition user-condition-1 (error) ())
(define-condition user-condition-2 (error) ())
 
Line 601 ⟶ 773:
 
(trace foo bar baz)
(foo)</langsyntaxhighlight>
 
{{out}} (the numbered lines are output from <code>trace</code>):
<langsyntaxhighlight lang="lisp"> 0: (FOO)
1: (BAR USER-CONDITION-1)
2: (BAZ USER-CONDITION-1)
foo: Caught: Condition USER-CONDITION-1 was signalled.
1: (BAR USER-CONDITION-2)
2: (BAZ USER-CONDITION-2)</langsyntaxhighlight>
 
At this point, the debugger (if any) is invoked
with the unhandled condition of type USER-CONDITION-2.
 
=={{header|Crystal}}==
 
<syntaxhighlight lang="ruby">class U0 < Exception
end
 
class U1 < Exception
end
 
def foo
2.times do |i|
begin
bar(i)
rescue e : U0
puts "rescued #{e}"
end
end
end
 
def bar(i : Int32)
baz(i)
end
 
def baz(i : Int32)
raise U0.new("this is u0") if i == 0
raise U1.new("this is u1") if i == 1
end
 
foo</syntaxhighlight>
 
<pre>
rescued this is u0
Unhandled exception: this is u1 (U1)
from exceptions_nested.cr:28:2 in 'baz'
from exceptions_nested.cr:23:2 in 'bar'
from exceptions_nested.cr:15:7 in 'foo'
from exceptions_nested.cr:31:1 in '__crystal_main'
from /usr/local/Cellar/crystal/0.32.1/src/crystal/main.cr:97:5 in 'main_user_code'
from /usr/local/Cellar/crystal/0.32.1/src/crystal/main.cr:86:7 in 'main'
from /usr/local/Cellar/crystal/0.32.1/src/crystal/main.cr:106:3 in 'main'
</pre>
 
=={{header|D}}==
First exception will be caught and message will be displayed,
second will be caught by default exception handler.
<langsyntaxhighlight lang="d">class U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }
}
Line 647 ⟶ 860:
void main() {
foo;
}</langsyntaxhighlight>
{{out}}
<pre>test.U1(at)test.d(8): U1 error message
Line 659 ⟶ 872:
=={{header|Delphi}}==
{{Trans|D}}
<langsyntaxhighlight lang="delphi">program ExceptionsInNestedCall;
 
{$APPTYPE CONSOLE}
Line 701 ⟶ 914:
begin
Foo;
end.</langsyntaxhighlight>
 
{{out}}
Line 709 ⟶ 922:
 
The uncaught exception shows a Windows Error Report dialog.
 
 
=={{header|DWScript}}==
{{Trans|D}}
First exception will be caught and message will be displayed, second will be caught by default exception handler.
<langsyntaxhighlight lang="delphi">type Exception1 = class (Exception) end;
type Exception2 = class (Exception) end;
 
Line 743 ⟶ 955:
end;
 
Foo;</langsyntaxhighlight>
Result:
<pre>Exception1 caught
User defined exception: Error message 2</pre>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">var bazCallCount = 0
func baz() {
bazCallCount += 1
if bazCallCount == 1 {
throw @BazCall1()
} else if bazCallCount == 2 {
throw @BazCall2()
}
}
func bar() {
baz()
}
func foo() {
var calls = 2
while calls > 0 {
try {
bar()
} catch {
@BazCall1() => print("BazzCall1 caught.")
}
calls -= 1
}
}
foo()</syntaxhighlight>
 
{{out}}
 
<pre>BazzCall1 caught.
Error D601: BazCall2</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define (foo)
(for ((i 2))
Line 771 ⟶ 1,019:
"U0 raised" catched
👓 error: U1 not catched
</syntaxhighlight>
</lang>
 
=={{header|EGL}}==
{{incorrect|EGL|calls to bar() from foo should be equivalent. Second call can't catch anything.}}
<syntaxhighlight lang="egl">record U0 type Exception
end
 
record U1 type Exception
end
 
program Exceptions
 
function main()
foo();
end
 
function foo()
try
bar();
onException(ex U0)
SysLib.writeStdout("Caught a U0 with message: '" :: ex.message :: "'");
end
bar();
end
 
function bar()
baz();
end
 
firstBazCall boolean = true;
function baz()
if(firstBazCall)
firstBazCall = false;
throw new U0{message = "This is the U0 exception"};
else
throw new U1{message = "This is the U1 exception"};
end
end
end</syntaxhighlight>
 
{{out}}
<pre>
Caught a U0 with message: 'This is the U0 exception'
This is the U1 exception
</pre>
 
=={{header|Eiffel}}==
Line 777 ⟶ 1,069:
 
A file called main.e:
<langsyntaxhighlight lang="eiffel">class MAIN
inherit EXCEPTIONS
 
Line 814 ⟶ 1,106:
end
end
end</langsyntaxhighlight>
 
{{out}}
Line 844 ⟶ 1,136:
Developer exception:</pre>
 
=={{header|EGLElena}}==
ELENA 6.x :
{{incorrect|EGL|calls to bar() from foo should be equivalent. Second call can't catch anything.}}
<syntaxhighlight lang="elena">import extensions;
<lang EGL>record U0 type Exception
end
class U0 : Exception
 
{
record U1 type Exception
constructor new()
end
<= super new("U0 exception");
 
}
program Exceptions
 
class U1 : Exception
function main()
{
foo();
constructor new()
end
<= super new("U1 exception");
 
}
function foo()
try
singleton Exceptions
bar();
{
onException(ex U0)
static int i;
SysLib.writeStdout("Caught a U0 with message: '" :: ex.message :: "'");
end
bar();
end <= baz();
 
function barbaz()
baz();{
end if (i == 0)
{
 
U0.raise()
firstBazCall boolean = true;
function baz() }
if(firstBazCall)else
{
firstBazCall = false;
U1.raise()
throw new U0{message = "This is the U0 exception"};
else}
}
throw new U1{message = "This is the U1 exception"};
end
endfoo()
{
end</lang>
for(i := 0; i < 2; i := i + 1)
 
{
try
{
self.bar()
}
catch(U0 e)
{
console.printLine("U0 Caught")
}
}
}
}
public program()
{
Exceptions.foo()
}</syntaxhighlight>
{{out}}
<pre>
U0 Caught
Caught a U0 with message: 'This is the U0 exception'
This is the U1 exception
Call stack:
sandbox'$private'Exceptions.baz[1]:sandbox.l(30)
sandbox'$private'Exceptions.foo[1]:sandbox.l(40)
sandbox'program.function:#invoke:sandbox.l(52)
system'$private'entry.function:#invoke:app.l(5)
system'$private'entrySymbol#sym:app.l(23)
 
Aborted:ffffffff
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule U0, do: defexception [:message]
defmodule U1, do: defexception [:message]
 
Line 909 ⟶ 1,226:
end
 
ExceptionsTest.foo</langsyntaxhighlight>
 
{{out}}
<pre>
U0 rescued
** (U1) got nil while retrieving Exception.message/1 for %U1{message: nil} (expected a string)
** (EXIT from #PID<0.48.0>) an exception was raised:
ExceptionsTest.exs:18: ExceptionsTest.baz/1
** (ArgumentError) argument error
ExceptionsTest.exs:8: anonymous fn/1 in ExceptionsTest.foo/0
:erlang.byte_size(nil)
(elixir) lib/exceptionenum.ex:106645: ExceptionEnum.format_banner"-each/2-lists^foreach/1-0-"/32
(elixir) lib/exceptionenum.ex:141645: ExceptionEnum.formateach/32
(elixir) lib/kernel/clicode.ex:113370: Kernel.CLICode.print_errorrequire_file/32
(elixir) lib/kernel/cli.ex:83: anonymous fn/3 in Kernel.CLI.exec_fun/2
</pre>
displayed message in version 1.4
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( exceptions_catch ).
 
Line 944 ⟶ 1,261:
 
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 954 ⟶ 1,271:
in call from exceptions_catch:'-task/0-lc$^0/1-0-'/1 (src/exceptions_catch.erl, line 5)
in call from exceptions_catch:'-task/0-lc$^0/1-0-'/1 (src/exceptions_catch.erl, line 5)
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators.extras continuations eval formatting kernel ;
IN: rosetta-code.nested-exceptions
 
ERROR: U0 ;
ERROR: U1 ;
 
: baz ( -- )
"IN: rosetta-code.nested-exceptions : baz ( -- ) U1 ;"
( -- ) eval U0 ;
 
: bar ( -- ) baz ;
 
: foo ( -- )
[
[ bar ] [
dup T{ U0 } =
[ "%u recovered\n" printf ] [ rethrow ] if
] recover
] twice ;
 
foo</syntaxhighlight>
{{out}}
<pre>
T{ U0 } recovered
U1
 
(U) Quotation: [ c-to-factor => ]
Word: c-to-factor
(U) Quotation: [ [ (get-catchstack) push ] dip call => (get-catchstack) pop* ]
(O) Word: command-line-startup
(O) Word: run-script
(O) Word: foo
(O) Word: baz
(O) Word: U1
(O) Method: M\ object throw
(U) Quotation: [
OBJ-CURRENT-THREAD special-object error-thread set-global
current-continuation => error-continuation set-global
[ original-error set-global ] [ rethrow ] bi
]
</pre>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
const class U0 : Err
{
Line 1,007 ⟶ 1,367:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,035 ⟶ 1,395:
The second exception is not handled, and results in the program finishing
and printing a stack trace.
 
=={{header|FreeBASIC}}==
FreeBASIC does not support exceptions or the Try/Catch/Finally statement, as such. However, you can use the Err() function, together with an If (or Switch) statement, to provide somewhat similar functionality:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Enum ErrorTypes
U0 = 1000
U1
End Enum
 
Function errorName(ex As ErrorTypes) As String
Select Case As Const ex
Case U0
Return "U0"
Case U1
Return "U1"
End Select
End Function
Sub catchError(ex As ErrorTypes)
Dim e As Integer = Err '' cache the error number
If e = ex Then
Print "Error "; errorName(ex); ", number"; ex; " caught"
End If
End Sub
 
Sub baz()
Static As Integer timesCalled = 0 '' persisted between procedure calls
timesCalled += 1
If timesCalled = 1 Then
err = U0
Else
err = U1
End if
End Sub
Sub bar()
baz
End Sub
 
Sub foo()
bar
catchError(U0) '' not interested in U1, assumed non-fatal
bar
catchError(U0)
End Sub
 
Foo
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Error U0, number 1000 caught
</pre>
 
=={{header|Go}}==
Line 1,047 ⟶ 1,463:
The solution here is to define a wrapper, or proxy function, called try.
Function foo calls bar indirectly through try.
<langsyntaxhighlight lang="go">// Outline for a try/catch-like exception mechanism in Go
//
// As all Go programmers should know, the Go authors are sharply critical of
Line 1,149 ⟶ 1,565:
}
trace("complete")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,187 ⟶ 1,603:
</pre>
A simpler example, closer to the task description:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,245 ⟶ 1,661:
foo()
fmt.Println("No panic")
}</langsyntaxhighlight>
[http://play.golang.org/p/X2pa8zE1Ce Run in Go Playground].
{{out}}
Line 1,257 ⟶ 1,673:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad.Error
import Control.Monad.Trans (lift)
 
Line 1,294 ⟶ 1,710:
case result of
Left e -> putStrLn ("Caught error at top level: " ++ show e)
Right v -> putStrLn ("Return value: " ++ show v)</langsyntaxhighlight>
 
{{out}}
Line 1,315 ⟶ 1,731:
not found in languages that natively support exceptions.</i>
 
<langsyntaxhighlight Uniconlang="unicon">import Exceptions
 
class U0 : Exception()
Line 1,359 ⟶ 1,775:
initial U0().throw("First exception")
U1().throw("Second exception")
end</langsyntaxhighlight>
 
{{out}}
Line 1,376 ⟶ 1,792:
Note: it may be possible to implement exceptions in Icon; however,
it would require a major rework and would likely be inelegant.
 
=={{header|Io}}==
<syntaxhighlight lang="io">U0 := Exception clone
U1 := Exception clone
 
foo := method(
for(i,1,2,
try(
bar(i)
)catch( U0,
"foo caught U0" print
)pass
)
)
bar := method(n,
baz(n)
)
baz := method(n,
if(n == 1,U0,U1) raise("baz with n = #{n}" interpolate)
)
 
foo</syntaxhighlight>
{{out}}
<pre>foo caught U0
U1: baz with n = 2
---------
U1 raise exceptions_catch_nested.io 34
Object baz exceptions_catch_nested.io 31
Object bar exceptions_catch_nested.io 24</pre>
The first line comes from when U0 was caught and the second from when U1 was raised and not caught. This is followed by a traceback with the most recent call first.
 
=={{header|J}}==
Line 1,382 ⟶ 1,828:
J leaves most of the implementation of exceptions to the programmer, so:
 
<langsyntaxhighlight Jlang="j">main=: monad define
smoutput 'main'
try. foo ''
Line 1,403 ⟶ 1,849:
smoutput ' baz'
type_jthrow_=: 'U',":y throw.
)</langsyntaxhighlight>
 
'''Example use:'''
<langsyntaxhighlight lang="j"> main ''
main
foo
Line 1,414 ⟶ 1,860:
bar
baz
main caught U1</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,422 ⟶ 1,868:
(or a superclass thereof), unless they are unchecked exceptions
(subclasses of <code>RuntimeException</code> or <code>Error</code>):
<langsyntaxhighlight lang="java">class U0 extends Exception { }
class U1 extends Exception { }
 
Line 1,450 ⟶ 1,896:
foo();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,477 ⟶ 1,923:
The <code>callee.name</code> property, and the <code>catch(e if ...)</code> statement are Mozilla JavaScript extensions.
 
<langsyntaxhighlight lang="javascript">function U() {}
U.prototype.toString = function(){return this.className;}
 
Line 1,511 ⟶ 1,957:
}
 
foo();</langsyntaxhighlight>
{{out}} from [[Rhino]]:
<pre>caught exception U0
Line 1,518 ⟶ 1,964:
<pre>caught exception U0
uncaught exception: U1</pre>
 
=={{header|jq}}==
{{works with|jq|>1.4}}
<langsyntaxhighlight lang="jq"># n is assumed to be the number of times baz has been previously called:
def baz(n):
if n==0 then error("U0")
Line 1,533 ⟶ 1,980:
(try bar(1) catch if . == "U0" then "We caught U0" else error(.) end);
 
foo</langsyntaxhighlight>
{{out}}
$ jq -n -f Catch_an_exception_thrown_in_a_nested_call.jq
"We caught U0"
jq: error: U1
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">struct U0 <: Exception end
struct U1 <: Exception end
 
function foo()
for i in 1:2
try
bar()
catch err
if isa(err, U0) println("catched U0")
else rethrow(err) end
end
end
end
 
function bar()
baz()
end
 
function baz()
if isdefined(:_called) && _called
throw(U1())
else
global _called = true
throw(U0())
end
end
 
foo()</syntaxhighlight>
 
{{out}}
<pre>catched U0
LoadError: U1()
while loading /home/giovanni/documents/workspace/julia/Rosetta-Julia/src/Catch_an_exception_thrown_in_a_nested_call.jl, in expression starting on line 31
in foo at Rosetta-Julia/src/Catch_an_exception_thrown_in_a_nested_call.jl:10
in baz at Rosetta-Julia/src/Catch_an_exception_thrown_in_a_nested_call.jl:24</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
class U0 : Throwable("U0 occurred")
class U1 : Throwable("U1 occurred")
 
fun foo() {
for (i in 1..2) {
try {
bar(i)
} catch(e: U0) {
println(e.message)
}
}
}
 
fun bar(i: Int) {
baz(i)
}
 
fun baz(i: Int) {
when (i) {
1 -> throw U0()
2 -> throw U1()
}
}
 
fun main(args: Array<String>) {
foo()
}</syntaxhighlight>
 
{{out}}
<pre>
U0 occurred
Exception in thread "main" U1: U1 occurred
at ExceptionsKt.baz(exceptions.kt:23)
at ExceptionsKt.bar(exceptions.kt:17)
at ExceptionsKt.foo(exceptions.kt:9)
at ExceptionsKt.main(exceptions.kt:28)
</pre>
 
=={{header|langur}}==
Exceptions in langur are hashes that are guaranteed to always contain certain fields.
 
There is no explicit try block. A catch implicitly wraps the instructions preceding it within a block into a try block.
 
<syntaxhighlight lang="langur">val .U0 = h{"msg": "U0"}
val .U1 = h{"msg": "U1"}
 
val .baz = fn(.i) { throw if(.i==0: .U0; .U1) }
val .bar = fn(.i) { .baz(.i) }
 
val .foo = impure fn() {
for .i in [0, 1] {
.bar(.i)
catch {
if _err'msg == .U0'msg {
writeln "caught .U0 in .foo()"
} else {
throw
}
}
}
}
 
.foo()
</syntaxhighlight>
 
{{out}}
<pre>caught .U0 in .foo()
VM Errors
general: U1 (.baz)</pre>
 
=={{header|Lasso}}==
Line 1,543 ⟶ 2,102:
but we can easily add one like so.
 
<langsyntaxhighlight Lassolang="lasso">define try(exception) => {
local(
gb = givenblock,
Line 1,582 ⟶ 2,141:
var(bazzed) ? fail('U1') | $bazzed = true
fail('U0')
}</langsyntaxhighlight>
 
{{out}}
Line 1,605 ⟶ 2,164:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">local baz_counter=1
function baz()
if baz_counter==1 then
Line 1,638 ⟶ 2,197:
 
foo()
</syntaxhighlight>
</lang>
output:
<pre>lua: errorexample.lua:31: U1
Line 1,647 ⟶ 2,206:
errorexample.lua:34: in main chunk
[C]: ?</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">baz := proc( which )
if ( which = 0 ) then
error "U0";
else
error "U1";
end;
end proc:
 
bar := proc( which )
baz( which );
end proc:
 
foo := proc()
local i;
for i from 0 to 1 do
try
bar(i);
catch "U0":
end;
end do;
end proc:
 
foo();</syntaxhighlight>
{{out}}
<syntaxhighlight lang="maple">Error, (in baz) U1</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">foo[] := Catch[ bar[1]; bar[2]; ]
 
bar[i_] := baz[i];
Line 1,655 ⟶ 2,241:
baz[i_] := Switch[i,
1, Throw["Exception U0 in baz"];,
2, Throw["Exception U1 in baz"];]</langsyntaxhighlight>
Output:
<pre> foo[]
Line 1,661 ⟶ 2,247:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function exceptionsCatchNestedCall()
function foo()
 
Line 1,691 ⟶ 2,277:
foo();
 
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> exceptionsCatchNestedCall()
message: [1x177 char]
identifier: 'BAZ:U0'
Line 1,702 ⟶ 2,288:
 
Error in ==> exceptionsCatchNestedCall at 29
foo();</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,755 ⟶ 2,341:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Exception U0 caught.
Line 1,765 ⟶ 2,351:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type U0 = object of Exception
type U1 = object of Exception
 
Line 1,782 ⟶ 2,368:
echo "Function foo caught exception U0"
 
foo()</langsyntaxhighlight>
{{out}}
<pre>Function foo caught exception U0
Line 1,794 ⟶ 2,380:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">@interface U0 : NSObject { }
@end
@interface U1 : NSObject { }
Line 1,836 ⟶ 2,422:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,845 ⟶ 2,431:
=={{header|OCaml}}==
Exceptions are used everywhere in OCaml, they are easy to write, and they are cheap.
<langsyntaxhighlight lang="ocaml">exception U0
exception U1
 
Line 1,861 ⟶ 2,447:
done
 
let () = foo ()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,870 ⟶ 2,456:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Exception Class new: U0
Exception Class new: U1
Line 1,880 ⟶ 2,466:
try: e [ 0 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
try: e [ 1 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
"Done" . ;</langsyntaxhighlight>
 
{{out}}
Line 1,893 ⟶ 2,479:
 
Exceptions are caught by pattern matching.
<langsyntaxhighlight lang="oz">declare
proc {Foo}
for I in 1..2 do
Line 1,913 ⟶ 2,499:
end
in
{Foo}</langsyntaxhighlight>
 
{{out}}
Line 1,928 ⟶ 2,514:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">call = 0;
 
U0() = error("x = ", 1, " should not happen!");
Line 1,934 ⟶ 2,520:
baz(x) = if(x==1, U0(), x==2, U1());x;
bar() = baz(call++);
foo() = if(!call, iferr(bar(), E, printf("Caught exception, call=%d",call)), bar())</langsyntaxhighlight>
 
Output 1. call to foo():<pre>Caught exception, call=1</pre>
Line 1,950 ⟶ 2,536:
</pre>
Output 3. call to foo():<pre>3</pre>
 
 
=={{header|Pascal}}==
Line 1,957 ⟶ 2,542:
=={{header|Perl}}==
Note: Both exceptions are caught and one is re-raised rather than only one being caught.
<langsyntaxhighlight lang="perl">sub foo {
foreach (0..1) {
eval { bar($_) };
Line 1,974 ⟶ 2,559:
}
 
foo();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,982 ⟶ 2,567:
</pre>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/basics}}
{{trans|Perl}}
Phix does not have "exception classes" as such, instead you can just throw any string (on it's own) or any integer, optionally
<lang perl6>sub foo() {
with any (deeply nested) user_data that you like. All exceptions are always caught, however rethrowing is trivial.<br>
for 0..1 -> $i {
As per the discussion for Go, I should say that "bar(); bar();" cannot work - if you catch an exception from the first call,
bar $i;
control resumes within the catch handler, with no way to invoke that second bar(). But a simple loop does the trick.
CATCH {
<!--<syntaxhighlight lang="phix">-->
when /U0/ { say "Function foo caught exception U0" }
<span style="color: #008080;">constant</span> <span style="color: #000000;">U0</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0<span style="color: #0000FF;">,</span>
}
<span style="color: #000000;">U1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
}
}
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">baz<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">U0<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #008000;">"any"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #008000;">"thing"<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #008000;">"you"<span style="color: #0000FF;">}<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #008000;">"like"<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">throw<span style="color: #0000FF;">(<span style="color: #000000;">U1<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;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">bar<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #000000;">baz<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">foo<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">try</span>
<span style="color: #000000;">bar<span style="color: #0000FF;">(<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;">U0</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?<span style="color: #000000;">e<span style="color: #0000FF;">[<span style="color: #000000;">E_USER<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: #000080;font-style:italic;">-- (terminates)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">try</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"still running...\n"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"not still running...\n"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">foo<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</syntaxhighlight>-->
{{out}}
<pre>
{{"any",{{"thing"},"you"}},"like"}
still running...
 
C:\Program Files (x86)\Phix\test.exw:27 in procedure foo()
sub bar($i) { baz $i }
unhandled exception
i = 2
e = {1,7533630,11,847,"baz","test.exw","C:\\Program Files (x86)\\Phix\\"}
... called from C:\Program Files (x86)\Phix\test.exw:35
 
Global & Local Variables
sub baz($i) { die "U$i" }
 
--> see C:\Program Files (x86)\Phix\ex.err
foo;</lang>
Press Enter...
{{out}}
</pre>
<pre>Function foo caught exception U0
Note that, unlike Python, the call stack from foo() to baz() has gone, for good, however e[E_LINE] is 11, indicating that unhandled exception originated from line 11 (ie "throw(U1)"), and if you need any more help than that, you'll have to arrange for it to end up in e[E_USER] manually.
U1
in sub baz at catch:12
in sub bar at catch:10
in sub foo at catch:4
in block at catch:14</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de foo ()
(for Tag '(U0 U1)
(catch 'U0
Line 2,019 ⟶ 2,641:
 
(mapc trace '(foo bar baz))
(foo)</langsyntaxhighlight>
{{out}}
<pre> foo :
Line 2,031 ⟶ 2,653:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Exceptions: Catch an exception thrown in a nested call */
test: proc options (main);
Line 2,062 ⟶ 2,684:
m = foo();
end test;
</syntaxhighlight>
</lang>
 
DESCRIPTION OF EXECUTION:
Line 2,094 ⟶ 2,716:
There is no extra syntax to add to functions and/or methods such as ''bar'',
to say what exceptions they may raise or pass through them:
<langsyntaxhighlight lang="python">class U0(Exception): pass
class U1(Exception): pass
 
Line 2,110 ⟶ 2,732:
raise U1 if i else U0
 
foo()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,132 ⟶ 2,754:
through the nested function calls together with the name of the
uncaught exception, (U1) to stderr, then quit the running program.
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ this ] is U0
 
[ this ] is U1
 
[ 0 = iff U0 else U1
message put bail ] is baz ( n --> )
 
[ baz ] is bar ( n --> )
 
[ 2 times
[ i^
1 backup
bar
bailed if
[ message share
U0 oats iff
[ say "Exception U0 raised." cr
echostack
$ "Press enter to continue"
input drop
message release
drop ]
else [ drop bail ] ] ] ] is foo</syntaxhighlight>
 
{{out}}
 
Testing in the Quackery shell, first with trapping the exception U1, and then without trapping the exception U1 (this is bad practice). Before invoking <code>foo</code> we put some arbitrary data on the stack to show if and how it is affected.
 
<pre>/O> 111 222 333
...
 
Stack: 111 222 333
 
/O> 0 backup foo bailed if [ message take echo ]
...
Exception U0 raised.
Stack: 111 222 333 0
Press enter to continue
U1
Stack: 111 222 333
 
/O> foo
...
Exception U0 raised.
Stack: 111 222 333 0
Press enter to continue
 
Problem: Cannot remove an immovable item.
Quackery Stack: 111 222 333
Return stack: {[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 0} {foo 2} {times 6}
{[...] 10} {[...] 6} {[...] 7} {[...] 1} {bail 1}
 
/O>
 
Stack empty.
</pre>
 
=={{header|R}}==
Line 2,138 ⟶ 2,819:
in your own environment.
See ?new.env and ?get.
<syntaxhighlight lang="r">
<lang r>
number_of_calls_to_baz <- 0
 
Line 2,154 ⟶ 2,835:
stop(e)
}
</syntaxhighlight>
</lang>
Example Usage:
<syntaxhighlight lang="r">
<lang r>
foo() # Error: U0
traceback()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,171 ⟶ 2,852:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,191 ⟶ 2,872:
(foo)
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
Function foo caught exception U0
. . failed 1
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" line>sub foo() {
for 0..1 -> $i {
bar $i;
CATCH {
when /U0/ { say "Function foo caught exception U0" }
}
}
}
 
sub bar($i) { baz $i }
 
sub baz($i) { die "U$i" }
 
foo;</syntaxhighlight>
{{out}}
<pre>Function foo caught exception U0
U1
in sub baz at catch:12
in sub bar at catch:10
in sub foo at catch:4
in block at catch:14</pre>
 
=={{header|REXX}}==
Line 2,202 ⟶ 2,908:
<br>This type of exception handling (in REXX) has its limitation &nbsp;
(the label is known global to the program, but not to external subroutines).
<langsyntaxhighlight lang="rexx">/*REXX program creates two exceptions and demonstrates how to handle (catch) them. */
call foo /*invoke the FOO function (below). */
say 'The REXX mainline program has completed.' /*indicate that Elroy was here. */
Line 2,223 ⟶ 2,929:
/* [↓] this U0 subroutine is ignored.*/
U0: return -1 /*handle exception if not caught. */
U1: return -1 /* " " " " " */</langsyntaxhighlight>
'''output'''
<pre>
Line 2,231 ⟶ 2,937:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def foo
2.times do |i|
begin
Line 2,253 ⟶ 2,959:
class U1 < StandardError; end
 
foo</langsyntaxhighlight>
The first call to foo causes the U0 exception. It gets rescued.
The second call results in a U1 exception which is not rescued,
Line 2,266 ⟶ 2,972:
from exception.rb:2:in `foo'
from exception.rb:23:in `<main>'</pre>
 
=={{header|Rust}}==
Rust has panics, which are similar to exceptions in that they default to unwinding the stack and the unwinding can be caught. However, panics can be configured to simply abort the program and thus cannot be guaranteed to be catchable. Panics should only be used for situations which are truly unexpected. It is prefered to return an Option or Result when a function can fail. <code>Result<T, U></code> is an enum (or sum type) with variants <code>Ok(T)</code> and <code>Err(U)</code>, representing a success value or failure value. <code>main</code> can return a Result, in which case the debug representation of the error will be shown.
<syntaxhighlight lang="rust">#[derive(Debug)]
enum U {
U0(i32),
U1(String),
}
 
fn baz(i: u8) -> Result<(), U> {
match i {
0 => Err(U::U0(42)),
1 => Err(U::U1("This will be returned from main".into())),
_ => Ok(()),
}
}
 
fn bar(i: u8) -> Result<(), U> {
baz(i)
}
 
fn foo() -> Result<(), U> {
for i in 0..2 {
match bar(i) {
Ok(()) => {},
Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n),
Err(e) => return Err(e),
}
}
Ok(())
}
 
fn main() -> Result<(), U> {
foo()
}</syntaxhighlight>
{{out}}
<pre>Caught U0 in foo: 42
Error: U1("This will be returned from main")</pre>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">object ExceptionsTest extends App {
class U0 extends Exception
class U1 extends Exception
Line 2,288 ⟶ 3,032:
foo
}
</syntaxhighlight>
</lang>
Exception U0 is caught, exception U1 is caught and re-thrown.
Program execution is terminated as the U1 exception is not caught
Line 2,297 ⟶ 3,041:
is not [http://seed7.sourceforge.net/manual/errors.htm#Handlers handled]
the program is terminated and a [http://seed7.sourceforge.net/manual/errors.htm#Stack_trace stack trace] is written.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const EXCEPTION: U0 is enumlit;
Line 2,332 ⟶ 3,076:
begin
foo;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,350 ⟶ 3,094:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func baz(i) { die "U#{i}" };
func bar(i) { baz(i) };
 
func foo {
[0, 1].each { |i|
try { bar(i) }
catch { |_, msg|
msg ~~ /^U0/  ? say "Function foo() caught exception U0"
 : die msg; # re-raise the exception
};
}
}
 
foo();</langsyntaxhighlight>
{{out}}
<pre>
Line 2,371 ⟶ 3,115:
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk/X}}functional code, not class based,
<syntaxhighlight lang="smalltalk">
using blocks as functions, and anonymous exceptions (signals):
Exception subclass: #U0.
<lang Smalltalk>| u0 u1 foo bar baz|
Exception subclass: #U1.
 
Object subclass: Foo [
u0 := Signal new.
u1 := Signal new.
 
foo bazCount := [0.
2 timesRepeat:[
[ bar value ]
on: u0
do:[ 'u0 cought' printCR ]
]
].
 
foo
bar := [
[2 baz valuetimesRepeat:
[ "==>" [self bar]. "<=="
on: U0
do:
[:sig |
'Call to bar was aborted by exception U0' printNl.
sig return]]]
 
bar
baz := [
|alreadyCalled|[self baz]
 
[baz
[bazCount := bazCount + 1.
alreadyCalled isNil ifTrue:[
bazCount = 1 ifTrue: [U0 new alreadyCalled := truesignal]. u0 raise
bazCount = 2 ] ifFalseifTrue: [U1 new signal].
"Thirds time's a u1 raise charm..."]
]
]
</syntaxhighlight>
]
] value.
 
Running the code:
foo value</lang>
<syntaxhighlight lang="smalltalk">
"traditional" implementation, using class based exceptions,
st> Foo new foo
and method invocations:
'Call to bar was aborted by exception U0'
<lang Smalltalk>Exception
Object: Foo new "<-0x4c9a7960>" error: An exception has occurred
subclass: #U0
U1(Exception)>>signal (ExcHandling.st:254)
instanceVariableNames:''
Foo>>baz (catch_exception.st:32)
classVariableNames:''
Foo>>bar (catch_exception.st:27)
poolDictionaries:''
optimized [] in Foo>>foo (catch_exception.st:19)
category:'example'.
BlockClosure>>on:do: (BlkClosure.st:193)
Foo>>foo (catch_exception.st:20)
UndefinedObject>>executeStatements (a String:1)
nil
</syntaxhighlight>
 
Explanation:<br/>
Exception
Inside the foo method, inside the 2 timesRepeat: block, there is a small
subclass: #U1
block <code>[self bar]</code> which simply calls bar. This block is sent
instanceVariableNames:''
the <code>#on:do:</code> message, which will evaluate the block and catch
classVariableNames:''
any mentioned exception. First time this block is evaluated, it results in
poolDictionaries:''
a U0 exception, which we catch and handle by printing a message and
category:'example'.
returning <code>nil</code> in place of whatever the block would have
returned. The second time the block is evaluated, it results in a U1
exception, which we do ''not'' catch, so it passes to the default handler
which prints a trace and exits. The second line of the trace
<code>U1(Exception)>>signal</code> shows that this was a U1 exception.
 
Exception handling in Smalltalk is exceptional, and the exception handler
Object
(the following do: block) can do quite some cool stuff, like retrying the
subclass: #CatchMeIfYouCan
block, retrying with a different block, and even resuming evaluation at the
instanceVariableNames:'bazAlreadyCalled'
point where the exception was raised (baz in this example) having <code>U0
classVariableNames:''
new signal</code> return some value.
poolDictionaries:''
category:'example'.
 
" CatchMeIfYouCan methods "
 
foo
2 timesRepeat:[
[ self bar ]
on: U0
do:[ 'U0 cought' printCR ]
]
 
bar
self baz
 
 
baz
bazAlreadyCalled isNil ifTrue:[
bazAlreadyCalled := true.
U0 raise
] ifFalse:[
U1 raise
]
 
CatchMeIfYouCan new foo</lang>
 
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<langsyntaxhighlight lang="swift">enum MyException : ErrorType {
case U0
case U1
Line 2,478 ⟶ 3,206:
}
 
try foo()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,489 ⟶ 3,217:
 
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc foo {} {
Line 2,514 ⟶ 3,242:
 
foo
foo</langsyntaxhighlight>
{{out}}
<pre>$ tclsh85 exceptions.tcl
Line 2,531 ⟶ 3,259:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(defex u0)
@(defex u1)
@(define baz (x))
Line 2,558 ⟶ 3,286:
@ (end)
@(end)
@(foo)</langsyntaxhighlight>
 
{{out|Run}}
Line 2,569 ⟶ 3,297:
1
</pre>
 
=={{header|uBasic/4tH}}==
uBasic/4tH only captures an exception when a procedure is called by the function TRY(). TRY() returns zero when no exception was thrown. It returns the non-zero errorcode when an exception was thrown. RAISE can only throw user exceptions. If a procedure is called using the normal PROC keyword exceptions are not caught.
<syntaxhighlight lang="uBasic/4tH">u = 0 ' this is U0
v = 1 ' this is U1
 
Proc _foo ' call foo
End
 
_foo
For x = u To v ' throw U0 to U1
If x = u ' catch U0
If Try(_bar(x)) Then ' try to execute bar
Print "Procedure foo caught exception U0"
EndIf ' catch exception and write msg
Else ' don't catch other exceptions
Proc _bar(x)
EndIf
Next
Return
 
_bar
Param (1) ' bar takes a single parameter
Proc _baz(a@) ' bar calls baz
Return
 
_baz
Param (1) ' baz takes a single parameter
Raise a@ ' baz throws the exception
Return</syntaxhighlight>
{{Out}}
<pre>Procedure foo caught exception U0
 
Q Exception raised, 16092559880829058:136</pre>
 
=={{header|Ursala}}==
Line 2,574 ⟶ 3,336:
if baz raises an exception.
The exception is caught or not by foo.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
baz =
Line 2,592 ⟶ 3,354:
guard(
:/'foo received this result from normal termination of bar:'+ bar,
'U0'?=z/~& :/'foo caught an exception with this error message:')</langsyntaxhighlight>
Note that the definition of bar includes no conditional (?) or exception
handling operators, and is written without regard for any exceptions.
Line 2,609 ⟶ 3,371:
baz threw a user-defined empty string exception
U1</pre>
 
=={{header|Visual Basic .NET}}==
 
<syntaxhighlight lang="vbnet">Class U0
Inherits Exception
End Class
 
Class U1
Inherits Exception
End Class
 
Module Program
Sub Main()
Foo()
End Sub
 
Sub Foo()
Try
Bar()
Bar()
Catch ex As U0
Console.WriteLine(ex.GetType.Name & " caught.")
End Try
End Sub
 
Sub Bar()
Baz()
End Sub
 
Sub Baz()
' Static local variable is persisted between calls of the method and is initialized only once.
Static firstCall As Boolean = True
If firstCall Then
firstCall = False
Throw New U0()
Else
Throw New U1()
End If
End Sub
End Module</syntaxhighlight>
 
Control passes to the Catch block after U0 is thrown, and so the second call to Bar() is not made.
 
{{out}}
<pre>U0 caught.</pre>
 
To prevent this, a loop can be used to run the entire Try statement twice:
 
<syntaxhighlight lang="vbnet"> Sub Foo()
For i = 1 To 2
Try
Bar()
Catch ex As U0
Console.WriteLine(ex.GetType().Name & " caught.")
End Try
Next
End Sub</syntaxhighlight>
 
{{out}}
<pre>U0 caught.
 
Unhandled Exception: U1: Exception of type 'U1' was thrown.
at Program.Baz() in Program.vb:line 34
at Program.Bar() in Program.vb:line 25
at Program.Foo() in Program.vb:line 17
at Program.Main() in Program.vb:line 11</pre>
 
=={{header|Wren}}==
As explained in the [[Exceptions#Wren]] task, 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.
 
We can use that approach here, re-throwing the second (uncaught) exception so that it terminates the script.
<syntaxhighlight lang="wren">var U0 = "U0"
var U1 = "U1"
 
var bazCalled = 0
 
var baz = Fn.new {
bazCalled = bazCalled + 1
Fiber.abort( (bazCalled == 1) ? U0 : U1 )
}
 
var bar = Fn.new {
baz.call()
}
 
var foo = Fn.new {
for (i in 1..2) {
var f = Fiber.new { bar.call() }
f.try()
var err = f.error
if (err == U0) {
System.print("Caught exception %(err)")
} else if (err == U1) {
Fiber.abort("Uncaught exception %(err) rethrown") // re-throw
}
}
}
 
foo.call()</syntaxhighlight>
 
{{out}}
<pre>
Caught exception U0
Uncaught exception U1 rethrown
[./exceptions_nested line 23] in new(_) block argument
[./exceptions_nested line 28] in (script)
</pre>
 
=={{header|XPL0}}==
The obvious solution is to simply do the catch error handling at the
point where the error is detected. However, XPL0's Restart intrinsic can
be used to do something similar to C++'s catch operation. This technique
avoids having to pass an error condition back up through several levels
of function calls. (Technically, these functions are actually procedures
because they don't return a value, but XPL0 doesn't enforce the
distinction.)
<syntaxhighlight lang "XPL0">func U0; \Exception caused by square root of negative value
real X;
X:= Sqrt(-42.);
 
func U1; \Exception caused by opening a non-existent file for input
int F;
F:= FOpen("unobtainium.txt", 0);
 
func Baz;
int CallNo;
[CallNo:= [1]; \static-like variable
if CallNo(0) = 1 then \first time Baz is called
[CallNo(0):= 2;
Text(0, "Calling U0^m^j");
Trap(false); \turn off error trapping to prevent program abort
U0;
Restart;
]
else \second time Baz is called
[Text(0, "Calling U1^m^j");
U1; \error trapping is still disabled
];
];
 
func Bar;
Baz;
 
func Foo;
Bar;
 
int Err;
[Err:= GetErr; \get the exception error after the program is restarted
if Err then \reading GetErr resets any error number to 0, = no error
[Text(0, "Error "); IntOut(0, Err); Text(0, " detected^m^j")];
Foo;
Text(0, "Finished^m^j");
] \second exception is pending, and it will be displayed
</syntaxhighlight>
{{out}}
<pre>
Calling U0
Error 10 detected
Calling U1
Finished
 
RUN-TIME ERROR 3: I/O
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class U0(Exception.Exception){fcn init{Exception.init("U0")}}
class U1(Exception.Exception){fcn init{Exception.init("U1")}}
 
Line 2,617 ⟶ 3,542:
fcn bar(e){baz(e)}
fcn baz(e){throw(e)}
foo()</langsyntaxhighlight>
{{out}}
<pre>
885

edits