Exceptions/Catch an exception thrown in a nested call: Difference between revisions
Exceptions/Catch an exception thrown in a nested call (view source)
Revision as of 19:04, 1 May 2024
, 1 month ago→{{header|langur}}
(fix code and add output) |
Langurmonkey (talk | contribs) |
||
(19 intermediate revisions by 9 users not shown) | |||
Line 18:
=={{header|11l}}==
{{trans|Python}}
<
T U1 {}
F baz(i)
I i == 0
X.throw U0()
E
X.throw U1()
F bar(i)
Line 37:
print(‘Function foo caught exception U0’)
foo()</
{{out}}
Line 46:
=={{header|Ada}}==
<
procedure Exceptions_From_Nested_Calls is
Line 76:
Foo;
end loop;
end Exceptions_From_Nested_Calls;</
{{out}}
<pre>
Line 88:
=={{header|Aime}}==
<
baz(integer i)
{
Line 128:
return 0;
}</
{{out}}
<pre>Exception `U0' thrown
Line 149:
c.f. [[Exceptions#ALGOL_68|ALGOL 68 Exceptions]] for more details.
<
INT value,
STRUCT(
Line 204:
FI;
foo</
{{out}}
<pre>
Line 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}}
<
⍝ Traps (exceptions) are just numbers
⍝ 500-999 are reserved for the user
Line 242 ⟶ 352:
⎕SIGNAL U0 U1[i]
∇
:EndNamespace</
{{out}}
Line 260 ⟶ 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.
<
global U1 := Exception("Second Exception")
Line 283 ⟶ 393:
else if ( calls = 2 )
throw U1
}</
The runtime error:
<pre>Error: Second Exception
Line 305 ⟶ 415:
The global ErrorLevel keeps track of the last error.
Here is one way to keep track of nested errors:
<syntaxhighlight lang="autohotkey">foo()
Return
Line 334 ⟶ 444:
ErrorLevel .= "U0"
Return 1
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
U0& = 123
U1& = 124
Line 364 ⟶ 474:
ENDCASE
ENDPROC
</syntaxhighlight>
{{out}} (the second message is output by the default error handler):
<pre>Exception U0 caught in foo
Line 387 ⟶ 497:
U0 and U1 are boring for debugging purposes. Added something to help with that.
<
#include <stdlib.h>
Line 508 ⟶ 618:
</syntaxhighlight>
{{out}}
<pre>Foo entering bar.
Line 524 ⟶ 634:
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.
<
class Exceptions
{
Line 555 ⟶ 665:
foo();
}
}</
{{out}}
Line 573 ⟶ 683:
aborting the task, typically with an error message.
<
class U0 {};
class U1 {};
Line 600 ⟶ 710:
std::cout<< "Should never get here!\n";
return 0;
}</
Result:
Line 610 ⟶ 720:
=={{header|Clojure}}==
<
(def U1 (ex-info "U1" {}))
Line 626 ⟶ 736:
(defn -main [& args]
(foo))</
{{output}}
Line 646 ⟶ 756:
=={{header|Common Lisp}}==
<
(define-condition user-condition-2 (error) ())
Line 663 ⟶ 773:
(trace foo bar baz)
(foo)</
{{out}} (the numbered lines are output from <code>trace</code>):
<
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)</
At this point, the debugger (if any) is invoked
Line 678 ⟶ 788:
=={{header|Crystal}}==
<
end
Line 703 ⟶ 813:
end
foo</
<pre>
Line 720 ⟶ 830:
First exception will be caught and message will be displayed,
second will be caught by default exception handler.
<
this() @safe pure nothrow { super("U0 error message"); }
}
Line 750 ⟶ 860:
void main() {
foo;
}</
{{out}}
<pre>test.U1(at)test.d(8): U1 error message
Line 762 ⟶ 872:
=={{header|Delphi}}==
{{Trans|D}}
<
{$APPTYPE CONSOLE}
Line 804 ⟶ 914:
begin
Foo;
end.</
{{out}}
Line 816 ⟶ 926:
{{Trans|D}}
First exception will be caught and message will be displayed, second will be caught by default exception handler.
<
type Exception2 = class (Exception) end;
Line 845 ⟶ 955:
end;
Foo;</
Result:
<pre>Exception1 caught
Line 852 ⟶ 962:
=={{header|Dyalect}}==
<
func baz() {
Line 879 ⟶ 989:
}
foo()</
{{out}}
Line 887 ⟶ 997:
=={{header|EchoLisp}}==
<
(define (foo)
(for ((i 2))
Line 909 ⟶ 1,019:
"U0 raised" catched
👓 error: U1 not catched
</syntaxhighlight>
=={{header|EGL}}==
{{incorrect|EGL|calls to bar() from foo should be equivalent. Second call can't catch anything.}}
<
end
Line 947 ⟶ 1,057:
end
end
end</
{{out}}
Line 959 ⟶ 1,069:
A file called main.e:
<
inherit EXCEPTIONS
Line 996 ⟶ 1,106:
end
end
end</
{{out}}
Line 1,027 ⟶ 1,137:
=={{header|Elena}}==
ELENA
<
class U0 : Exception
{
}
class U1 : Exception
{
}
singleton Exceptions
{
}
}
Line 1,080 ⟶ 1,190:
{
Exceptions.foo()
}</
{{out}}
<pre>
U0 Caught
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}}==
<
defmodule U1, do: defexception [:message]
Line 1,117 ⟶ 1,226:
end
ExceptionsTest.foo</
{{out}}
Line 1,132 ⟶ 1,241:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( exceptions_catch ).
Line 1,152 ⟶ 1,261:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,165 ⟶ 1,274:
=={{header|Factor}}==
<
IN: rosetta-code.nested-exceptions
Line 1,185 ⟶ 1,294:
] twice ;
foo</
{{out}}
<pre>
Line 1,209 ⟶ 1,318:
=={{header|Fantom}}==
<
const class U0 : Err
{
Line 1,258 ⟶ 1,367:
}
}
</syntaxhighlight>
{{out}}
Line 1,289 ⟶ 1,398:
=={{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:
<
Enum ErrorTypes
Line 1,336 ⟶ 1,445:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,354 ⟶ 1,463:
The solution here is to define a wrapper, or proxy function, called try.
Function foo calls bar indirectly through try.
<
//
// As all Go programmers should know, the Go authors are sharply critical of
Line 1,456 ⟶ 1,565:
}
trace("complete")
}</
{{out}}
<pre>
Line 1,494 ⟶ 1,603:
</pre>
A simpler example, closer to the task description:
<
import "fmt"
Line 1,552 ⟶ 1,661:
foo()
fmt.Println("No panic")
}</
[http://play.golang.org/p/X2pa8zE1Ce Run in Go Playground].
{{out}}
Line 1,564 ⟶ 1,673:
=={{header|Haskell}}==
<
import Control.Monad.Trans (lift)
Line 1,601 ⟶ 1,710:
case result of
Left e -> putStrLn ("Caught error at top level: " ++ show e)
Right v -> putStrLn ("Return value: " ++ show v)</
{{out}}
Line 1,622 ⟶ 1,731:
not found in languages that natively support exceptions.</i>
<
class U0 : Exception()
Line 1,666 ⟶ 1,775:
initial U0().throw("First exception")
U1().throw("Second exception")
end</
{{out}}
Line 1,685 ⟶ 1,794:
=={{header|Io}}==
<
U1 := Exception clone
Line 1,704 ⟶ 1,813:
)
foo</
{{out}}
<pre>foo caught U0
Line 1,719 ⟶ 1,828:
J leaves most of the implementation of exceptions to the programmer, so:
<
smoutput 'main'
try. foo ''
Line 1,740 ⟶ 1,849:
smoutput ' baz'
type_jthrow_=: 'U',":y throw.
)</
'''Example use:'''
<
main
foo
Line 1,751 ⟶ 1,860:
bar
baz
main caught U1</
=={{header|Java}}==
Line 1,759 ⟶ 1,868:
(or a superclass thereof), unless they are unchecked exceptions
(subclasses of <code>RuntimeException</code> or <code>Error</code>):
<
class U1 extends Exception { }
Line 1,787 ⟶ 1,896:
foo();
}
}</
{{out}}
<pre>
Line 1,814 ⟶ 1,923:
The <code>callee.name</code> property, and the <code>catch(e if ...)</code> statement are Mozilla JavaScript extensions.
<
U.prototype.toString = function(){return this.className;}
Line 1,848 ⟶ 1,957:
}
foo();</
{{out}} from [[Rhino]]:
<pre>caught exception U0
Line 1,858 ⟶ 1,967:
=={{header|jq}}==
{{works with|jq|>1.4}}
<
def baz(n):
if n==0 then error("U0")
Line 1,871 ⟶ 1,980:
(try bar(1) catch if . == "U0" then "We caught U0" else error(.) end);
foo</
{{out}}
$ jq -n -f Catch_an_exception_thrown_in_a_nested_call.jq
Line 1,880 ⟶ 1,989:
{{works with|Julia|0.6}}
<
struct U1 <: Exception end
Line 1,907 ⟶ 2,016:
end
foo()</
{{out}}
Line 1,917 ⟶ 2,026:
=={{header|Kotlin}}==
<
class U0 : Throwable("U0 occurred")
Line 1,945 ⟶ 2,054:
fun main(args: Array<String>) {
foo()
}</
{{out}}
Line 1,962 ⟶ 2,071:
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 =
val .bar =
val .foo =
for .i in [0, 1] {
.bar(.i)
catch
if _err'msg
} else
}
}
}
}
.foo()
</syntaxhighlight>
{{out}}
Line 1,992 ⟶ 2,102:
but we can easily add one like so.
<
local(
gb = givenblock,
Line 2,031 ⟶ 2,141:
var(bazzed) ? fail('U1') | $bazzed = true
fail('U0')
}</
{{out}}
Line 2,054 ⟶ 2,164:
=={{header|Lua}}==
<
function baz()
if baz_counter==1 then
Line 2,087 ⟶ 2,197:
foo()
</syntaxhighlight>
output:
<pre>lua: errorexample.lua:31: U1
Line 2,098 ⟶ 2,208:
=={{header|Maple}}==
<
if ( which = 0 ) then
error "U0";
Line 2,120 ⟶ 2,230:
end proc:
foo();</
{{out}}
<syntaxhighlight lang
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
bar[i_] := baz[i];
Line 2,131 ⟶ 2,241:
baz[i_] := Switch[i,
1, Throw["Exception U0 in baz"];,
2, Throw["Exception U1 in baz"];]</
Output:
<pre> foo[]
Line 2,137 ⟶ 2,247:
=={{header|MATLAB}} / {{header|Octave}}==
<
function foo()
Line 2,167 ⟶ 2,277:
foo();
end</
{{out}}
<
message: [1x177 char]
identifier: 'BAZ:U0'
Line 2,178 ⟶ 2,288:
Error in ==> exceptionsCatchNestedCall at 29
foo();</
=={{header|Nemerle}}==
<
using System.Console;
Line 2,231 ⟶ 2,341:
}
}
}</
{{out}}
<pre>Exception U0 caught.
Line 2,241 ⟶ 2,351:
=={{header|Nim}}==
<
type U1 = object of Exception
Line 2,258 ⟶ 2,368:
echo "Function foo caught exception U0"
foo()</
{{out}}
<pre>Function foo caught exception U0
Line 2,270 ⟶ 2,380:
=={{header|Objective-C}}==
<
@end
@interface U1 : NSObject { }
Line 2,312 ⟶ 2,422:
}
return 0;
}</
{{out}}
<pre>
Line 2,321 ⟶ 2,431:
=={{header|OCaml}}==
Exceptions are used everywhere in OCaml, they are easy to write, and they are cheap.
<
exception U1
Line 2,337 ⟶ 2,447:
done
let () = foo ()</
{{out}}
<pre>
Line 2,346 ⟶ 2,456:
=={{header|Oforth}}==
<
Exception Class new: U1
Line 2,356 ⟶ 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" . ;</
{{out}}
Line 2,369 ⟶ 2,479:
Exceptions are caught by pattern matching.
<
proc {Foo}
for I in 1..2 do
Line 2,389 ⟶ 2,499:
end
in
{Foo}</
{{out}}
Line 2,404 ⟶ 2,514:
=={{header|PARI/GP}}==
<
U0() = error("x = ", 1, " should not happen!");
Line 2,410 ⟶ 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())</
Output 1. call to foo():<pre>Caught exception, call=1</pre>
Line 2,432 ⟶ 2,542:
=={{header|Perl}}==
Note: Both exceptions are caught and one is re-raised rather than only one being caught.
<
foreach (0..1) {
eval { bar($_) };
Line 2,449 ⟶ 2,559:
}
foo();</
{{out}}
<pre>
Line 2,463 ⟶ 2,573:
As per the discussion for Go, I should say that "bar(); bar();" cannot work - if you catch an exception from the first call,
control resumes within the catch handler, with no way to invoke that second bar(). But a simple loop does the trick.
<!--<
<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>
Line 2,499 ⟶ 2,609:
<span style="color: #000000;">foo<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</
{{out}}
<pre>
Line 2,519 ⟶ 2,629:
=={{header|PicoLisp}}==
<
(for Tag '(U0 U1)
(catch 'U0
Line 2,531 ⟶ 2,641:
(mapc trace '(foo bar baz))
(foo)</
{{out}}
<pre> foo :
Line 2,543 ⟶ 2,653:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Exceptions: Catch an exception thrown in a nested call */
test: proc options (main);
Line 2,574 ⟶ 2,684:
m = foo();
end test;
</syntaxhighlight>
DESCRIPTION OF EXECUTION:
Line 2,606 ⟶ 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:
<
class U1(Exception): pass
Line 2,622 ⟶ 2,732:
raise U1 if i else U0
foo()</
{{out}}
<pre>
Line 2,647 ⟶ 2,757:
=={{header|Quackery}}==
<
[ this ] is U1
Line 2,669 ⟶ 2,779:
message release
drop ]
else [ drop bail ] ] ] ] is foo</
{{out}}
Line 2,709 ⟶ 2,819:
in your own environment.
See ?new.env and ?get.
<syntaxhighlight lang="r">
number_of_calls_to_baz <- 0
Line 2,725 ⟶ 2,835:
stop(e)
}
</syntaxhighlight>
Example Usage:
<syntaxhighlight lang="r">
foo() # Error: U0
traceback()
</syntaxhighlight>
{{out}}
<pre>
Line 2,742 ⟶ 2,852:
=={{header|Racket}}==
<
#lang racket
Line 2,762 ⟶ 2,872:
(foo)
</syntaxhighlight>
{{out}}
<
Function foo caught exception U0
. . failed 1
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku"
for 0..1 -> $i {
bar $i;
Line 2,785 ⟶ 2,895:
sub baz($i) { die "U$i" }
foo;</
{{out}}
<pre>Function foo caught exception U0
Line 2,798 ⟶ 2,908:
<br>This type of exception handling (in REXX) has its limitation
(the label is known global to the program, but not to external subroutines).
<
call foo /*invoke the FOO function (below). */
say 'The REXX mainline program has completed.' /*indicate that Elroy was here. */
Line 2,819 ⟶ 2,929:
/* [↓] this U0 subroutine is ignored.*/
U0: return -1 /*handle exception if not caught. */
U1: return -1 /* " " " " " */</
'''output'''
<pre>
Line 2,827 ⟶ 2,937:
=={{header|Ruby}}==
<
2.times do |i|
begin
Line 2,849 ⟶ 2,959:
class U1 < StandardError; end
foo</
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,865 ⟶ 2,975:
=={{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.
<
enum U {
U0(i32),
Line 2,896 ⟶ 3,006:
fn main() -> Result<(), U> {
foo()
}</
{{out}}
<pre>Caught U0 in foo: 42
Line 2,903 ⟶ 3,013:
=={{header|Scala}}==
{{libheader|Scala}}
<
class U0 extends Exception
class U1 extends Exception
Line 2,922 ⟶ 3,032:
foo
}
</syntaxhighlight>
Exception U0 is caught, exception U1 is caught and re-thrown.
Program execution is terminated as the U1 exception is not caught
Line 2,931 ⟶ 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.
<
const EXCEPTION: U0 is enumlit;
Line 2,966 ⟶ 3,076:
begin
foo;
end func;</
{{out}}
Line 2,984 ⟶ 3,094:
=={{header|Sidef}}==
<
func bar(i) { baz(i) }
func foo {
[0, 1].each { |i|
try { bar(i) }
catch { |
msg ~~ /^U0/
}
}
}
foo()
{{out}}
<pre>
Line 3,006 ⟶ 3,116:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
Exception subclass: #U0.
Exception subclass: #U1.
Line 3,032 ⟶ 3,142:
"Thirds time's a charm..."]
]
</syntaxhighlight>
Running the code:
<syntaxhighlight lang="smalltalk">
st> Foo new foo
'Call to bar was aborted by exception U0'
Line 3,047 ⟶ 3,157:
UndefinedObject>>executeStatements (a String:1)
nil
</syntaxhighlight>
Explanation:<br/>
Line 3,069 ⟶ 3,179:
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
case U0
case U1
Line 3,096 ⟶ 3,206:
}
try foo()</
{{out}}
<pre>
Line 3,107 ⟶ 3,217:
{{works with|Tcl|8.5}}
<
proc foo {} {
Line 3,132 ⟶ 3,242:
foo
foo</
{{out}}
<pre>$ tclsh85 exceptions.tcl
Line 3,149 ⟶ 3,259:
=={{header|TXR}}==
<
@(defex u1)
@(define baz (x))
Line 3,176 ⟶ 3,286:
@ (end)
@(end)
@(foo)</
{{out|Run}}
Line 3,187 ⟶ 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 3,192 ⟶ 3,336:
if baz raises an exception.
The exception is caught or not by foo.
<
baz =
Line 3,210 ⟶ 3,354:
guard(
:/'foo received this result from normal termination of bar:'+ bar,
'U0'?=z/~& :/'foo caught an exception with this error message:')</
Note that the definition of bar includes no conditional (?) or exception
handling operators, and is written without regard for any exceptions.
Line 3,230 ⟶ 3,374:
=={{header|Visual Basic .NET}}==
<
Inherits Exception
End Class
Line 3,266 ⟶ 3,410:
End If
End Sub
End Module</
Control passes to the Catch block after U0 is thrown, and so the second call to Bar() is not made.
Line 3,275 ⟶ 3,419:
To prevent this, a loop can be used to run the entire Try statement twice:
<
For i = 1 To 2
Try
Line 3,283 ⟶ 3,427:
End Try
Next
End Sub</
{{out}}
Line 3,298 ⟶ 3,442:
We can use that approach here, re-throwing the second (uncaught) exception so that it terminates the script.
<
var U1 = "U1"
Line 3,325 ⟶ 3,469:
}
foo.call()</
{{out}}
Line 3,333 ⟶ 3,477:
[./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}}==
<
class U1(Exception.Exception){fcn init{Exception.init("U1")}}
Line 3,342 ⟶ 3,542:
fcn bar(e){baz(e)}
fcn baz(e){throw(e)}
foo()</
{{out}}
<pre>
|