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

Content added Content deleted
Line 1: Line 1:
{{task}}
{{task}}
{{omit from|C}}
Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
{{omit from|GUISS}}
{{omit from|M4}}
{{omit from|Retro}}

Show how to create a user-defined exception and
show how to catch an exception raised from several nested calls away.


# Create two user-defined exceptions, U0 and U1.
# Create two user-defined exceptions, U0 and U1.
Line 41: Line 47:
end loop;
end loop;
end Exceptions_From_Nested_Calls;</lang>
end Exceptions_From_Nested_Calls;</lang>
{{out}}
Sample output:
<pre>
<pre>
Procedure Foo caught exception U0
Procedure Foo caught exception U0
Line 47: Line 53:
raised EXCEPTIONS_FROM_NESTED_CALLS.U1 : exceptions_from_nested_calls.adb:13
raised EXCEPTIONS_FROM_NESTED_CALLS.U1 : exceptions_from_nested_calls.adb:13
</pre>
</pre>
An unhandled exception leads to termination of the corresponding [[task]]. When the task is the main task of the program as in the example, the whole program is terminated. In the example the exception back tracing message is compiler-specific (in this case it is [[GNAT]] and further depends on the compiler options.
An unhandled exception leads to termination of the corresponding [[task]].
When the task is the main task of the program as in the example, the whole program is terminated. In the example the exception back tracing message is compiler-specific
(in this case it is [[GNAT]] and further depends on the compiler options.


=={{header|Aime}}==
=={{header|Aime}}==
Line 167: Line 175:


foo</lang>
foo</lang>
{{out}}
Output:
<pre>
<pre>
Function foo caught exception u0
Function foo caught exception u0
Line 291: Line 299:
ENDPROC
ENDPROC
</lang>
</lang>
Output (the second message is output by the default error handler):
{{out}} (the second message is output by the default error handler):
<pre>Exception U0 caught in foo
<pre>Exception U0 caught in foo


Line 435: Line 443:


</lang>
</lang>
{{out}}
Output:
<lang>Foo entering bar.
<pre>Foo entering bar.
Bar door is open.
Bar door is open.
Bar door is closed.
Bar door is closed.
Line 445: Line 453:
Bar door is closed.
Bar door is closed.
*** Error: U1 Bartender Error. Bartender kicked customer out of bar Baz.
*** Error: U1 Bartender Error. Bartender kicked customer out of bar Baz.
</lang>
</pre>


=={{header|C++}}==
=={{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,
First exception will be caught and message will be displayed,
second will be caught by the default exception handler,
typically with an error message.
which as required by the C++ Standard, will call terminate(),
aborting the task, typically with an error message.


<lang cpp>#include <iostream>
<lang cpp>#include <iostream>
Line 523: Line 533:
}</lang>
}</lang>


{{out}}
Output:
<pre>
<pre>
U0 Caught
U0 Caught
Line 555: Line 565:
(foo)</lang>
(foo)</lang>


Sample output (the numbered lines are output from <code>trace</code>):
{{out}} (the numbered lines are output from <code>trace</code>):

<lang lisp> 0: (FOO)
<lang lisp> 0: (FOO)
1: (BAR USER-CONDITION-1)
1: (BAR USER-CONDITION-1)
Line 564: Line 573:
2: (BAZ USER-CONDITION-2)</lang>
2: (BAZ USER-CONDITION-2)</lang>


At this point, the debugger (if any) is invoked with the unhandled condition of type USER-CONDITION-2.
At this point, the debugger (if any) is invoked
with the unhandled condition of type USER-CONDITION-2.


=={{header|D}}==
=={{header|D}}==
First exception will be caught and message will be displayed, second will be caught by default exception handler.
First exception will be caught and message will be displayed,
second will be caught by default exception handler.
<lang d>class U0 : Exception {
<lang d>class U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }
this() @safe pure nothrow { super("U0 error message"); }
Line 599: Line 610:
foo;
foo;
}</lang>
}</lang>
{{output}}
{{out}}
<pre>test.U1(at)test.d(8): U1 error message
<pre>test.U1(at)test.d(8): U1 error message
----------------
----------------
Line 654: Line 665:
end.</lang>
end.</lang>


{{out}}
Output:
<pre>
<pre>
Exception U0 caught
Exception U0 caught
Line 742: Line 753:
end</lang>
end</lang>


{{out}}
Sample output:
<pre>Caught U0 exception.
<pre>Caught U0 exception.
Won't catch U1 exception...
Won't catch U1 exception...
Line 808: Line 819:
end</lang>
end</lang>


{{out}}
Output:
<pre>
<pre>
Caught a U0 with message: 'This is the U0 exception'
Caught a U0 with message: 'This is the U0 exception'
Line 900: Line 911:
</lang>
</lang>


{{out}}
Output:

<pre>
<pre>
Caught U0
Caught U0
Line 924: Line 934:
</pre>
</pre>


The output shows the first exception is caught and handled. The second exception is not handled, and results in the program finishing and printing a stack trace.
The output shows the first exception is caught and handled.
The second exception is not handled, and results in the program finishing
and printing a stack trace.


=={{header|Go}}==
=={{header|Go}}==
Not strictly conforming to task description as foo does not directly call bar.
Not strictly conforming to task description as foo does not directly call bar.


The panic/recover mechanism of Go is missing (by design)
The panic/recover mechanism of Go is missing (by design) some elements of exception handling needed for this task. Specifically, a function that recovers a panic cannot resume execution of the remainder of the function. If foo recovers a panic in the first call to bar, there is no way for it to make the second call to bar. The solution here is to define a wrapper, or proxy function, called try. Function foo calls bar indirectly through try.
some elements of exception handling needed for this task.
Specifically, a function that recovers a panic cannot resume
execution of the remainder of the function.
If foo recovers a panic in the first call to bar, there is no way for it
to make the second call to bar.
The solution here is to define a wrapper, or proxy function, called try.
Function foo calls bar indirectly through try.
<lang go>// Outline for a try/catch-like exception mechanism in Go
<lang go>// Outline for a try/catch-like exception mechanism in Go
//
//
Line 1,179: Line 1,198:
Right v -> putStrLn ("Return value: " ++ show v)</lang>
Right v -> putStrLn ("Return value: " ++ show v)</lang>


{{out}}
The output of this program is:
<pre>

foo
foo
bar
bar
Line 1,188: Line 1,207:
baz
baz
Caught error at top level: U1
Caught error at top level: U1
</pre>


==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==


The following Unicon example makes use of support for exceptions found in the
The following Unicon example makes use of support for exceptions found
[http://tapestry.tucson.az.us/unilib/ The Unicon Code Library]. <i>Since
in the [http://tapestry.tucson.az.us/unilib/ The Unicon Code Library].
exception support is not built into Unicon, but rather implemented as
<i>Since exception support is not built into Unicon,
Unicon code, there are limitations not found in languages that natively
but rather implemented as Unicon code, there are limitations
support exceptions.</i>
not found in languages that natively support exceptions.</i>


<lang Unicon>import Exceptions
<lang Unicon>import Exceptions
Line 1,243: Line 1,263:
end</lang>
end</lang>


{{out}}
When run, this example produces:
<pre>
<pre>
U0: First exception:
U0: First exception:
Line 1,256: Line 1,276:
</pre>
</pre>


Note: it may be possible to implement exceptions in Icon; however, it would require a major rework and would likely be inelegant.
Note: it may be possible to implement exceptions in Icon; however,
it would require a major rework and would likely be inelegant.


=={{header|J}}==
=={{header|J}}==
Line 1,298: Line 1,319:


=={{header|Java}}==
=={{header|Java}}==
Methods that may throw an exception (or that call a method
Methods that may throw an exception (or that call a method that may throw an exception that it does not catch) must explicitly declare that they can throw such an exception (or a superclass thereof), unless they are unchecked exceptions (subclasses of <code>RuntimeException</code> or <code>Error</code>):
that may throw an exception that it does not catch)
must explicitly declare that they can throw such an exception
(or a superclass thereof), unless they are unchecked exceptions
(subclasses of <code>RuntimeException</code> or <code>Error</code>):
<lang java>class U0 extends Exception { }
<lang java>class U0 extends Exception { }
class U1 extends Exception { }
class U1 extends Exception { }
Line 1,328: Line 1,353:
}
}
}</lang>
}</lang>
{{out}}
Sample output:
<pre>
<pre>
Function foo caught exception U0
Function foo caught exception U0
Line 1,337: Line 1,362:
at ExceptionsTest.main(ExceptionsTest.java:27)
at ExceptionsTest.main(ExceptionsTest.java:27)
</pre>
</pre>
The first line of the output is generated from catching the U0 exception in function foo.
The first line of the output is generated from catching the U0 exception
in function foo.


Uncaught exceptions give information showing where the exception originated through the nested function calls together with the name of the uncaught exception, (U1) to stderr, then quit the running program.
Uncaught exceptions give information showing where the exception
originated through the nested function calls together with the name
of the uncaught exception, (U1) to stderr,
then quit the running program.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,385: Line 1,414:


foo();</lang>
foo();</lang>
[[Rhino]] output:
{{out}} from [[Rhino]]:
<pre>caught exception U0
<pre>caught exception U0
js: "nested_calls.js", line 31: exception from uncaught JavaScript throw: U1</pre>
js: "nested_calls.js", line 31: exception from uncaught JavaScript throw: U1</pre>
[[SpiderMonkey]] output:
{{out}} from [[SpiderMonkey]]:
<pre>caught exception U0
<pre>caught exception U0
uncaught exception: U1</pre>
uncaught exception: U1</pre>


=={{header|Lasso}}==
=={{header|Lasso}}==
Lasso currently does not currently have a try mechanic — but we can easily add one like so.
Lasso currently does not currently have a try mechanic —
but we can easily add one like so.


<lang Lasso>define try(exception) => {
<lang Lasso>define try(exception) => {
Line 1,609: Line 1,639:
}
}
}</lang>
}</lang>
{{out}}
Output:
<pre>Exception U0 caught.
<pre>Exception U0 caught.


Line 1,636: Line 1,666:


foo()</lang>
foo()</lang>
{{out}}
Output:
<pre>Function foo caught exception U0
<pre>Function foo caught exception U0
Traceback (most recent call last)
Traceback (most recent call last)
Line 1,690: Line 1,720:
return 0;
return 0;
}</lang>
}</lang>
{{out}}
Sample output:
<pre>
<pre>
2011-06-03 23:11:53.871 Untitled[9968:903] Function foo caught exception U0
2011-06-03 23:11:53.871 Untitled[9968:903] Function foo caught exception U0
Line 1,746: Line 1,776:
{Foo}</lang>
{Foo}</lang>


{{out}}
Sample output:
<pre>
<pre>
Procedure Foo caught exception u0
Procedure Foo caught exception u0
Line 1,781: Line 1,811:


foo();</lang>
foo();</lang>
{{out}}
Sample output:
<pre>
<pre>
Function foo caught exception U0
Function foo caught exception U0
Line 1,826: Line 1,856:
(mapc trace '(foo bar baz))
(mapc trace '(foo bar baz))
(foo)</lang>
(foo)</lang>
{{out}}
Output:
<pre> foo :
<pre> foo :
bar : U0
bar : U0
Line 1,898: Line 1,928:


=={{header|Python}}==
=={{header|Python}}==
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:
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:
<lang python>class U0(Exception): pass
<lang python>class U0(Exception): pass
class U1(Exception): pass
class U1(Exception): pass
Line 1,916: Line 1,947:


foo()</lang>
foo()</lang>
{{out}}
Sample output:
<pre>
<pre>
Function foo caught exception U0
Function foo caught exception U0
Line 1,931: Line 1,962:
U1
U1
</pre>
</pre>
The first line of the output is generated from catching the U0 exception in function foo.
The first line of the output is generated from catching the U0 exception
in function foo.


Uncaught exceptions give information showing where the exception originated through the nested function calls together with the name of the uncaught exception, (U1) to stderr, then quit the running program.
Uncaught exceptions give information showing where the exception originated
through the nested function calls together with the name of the
uncaught exception, (U1) to stderr, then quit the running program.


=={{header|R}}==
=={{header|R}}==
The counter for the number of calls to baz is kept in the global environment for simplicity, but you could hide it in your own environment. See ?new.env and ?get.
The counter for the number of calls to baz is kept in
the global environment for simplicity, but you could hide it
in your own environment.
See ?new.env and ?get.
<lang r>
<lang r>
number_of_calls_to_baz <- 0
number_of_calls_to_baz <- 0
Line 1,959: Line 1,996:
traceback()
traceback()
</lang>
</lang>
{{out}}
<pre>
<pre>
6: stop(e) at file.r#11
6: stop(e) at file.r#11
Line 1,990: Line 2,028:
(foo)
(foo)
</lang>
</lang>
{{out}}
Output:
<lang racket>
<lang racket>
Function foo caught exception U0
Function foo caught exception U0
Line 1,997: Line 2,035:


=={{header|REXX}}==
=={{header|REXX}}==
While the REXX language doesn't have a ''throw'' capability ''pe se'', it does have the ability to catch exceptions (by label).
While the REXX language doesn't have a ''throw'' capability ''pe se'',
it does have the ability to catch exceptions (by label).
<br>This type of exception handling (in REXX) has its limitation (the label is local to the program, not external subroutines).
<br>This type of exception handling (in REXX) has its limitation
(the label is local to the program, not external subroutines).
<lang rexx>/*REXX program to create two exceptions & demonstrate how to handle them*/
<lang rexx>/*REXX program to create two exceptions & demonstrate how to handle them*/
call foo /*invoke the FOO function. */
call foo /*invoke the FOO function. */
Line 2,022: Line 2,062:
U0: return -1 /*handle exception if not caught.*/
U0: return -1 /*handle exception if not caught.*/
U1: return -1 /* " " " " " */</lang>
U1: return -1 /* " " " " " */</lang>
{{out}}
'''output'''
<pre style="overflow:scroll">
<pre style="overflow:scroll">
exception U0 caught in FOO
exception U0 caught in FOO
Line 2,054: Line 2,094:
foo
foo
foo </lang>
foo </lang>
The first call to foo causes the U0 exception. It gets rescued. The second call results in a U1 exception which is not rescued, so the program dumps a stacktrace and exits.
The first call to foo causes the U0 exception. It gets rescued.
The second call results in a U1 exception which is not rescued,
so the program dumps a stacktrace and exits.
{{out}}
{{out}}
<pre>$ ruby test2.rb
<pre>$ ruby test2.rb
Line 2,065: Line 2,107:


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
[[Category:Scala Implementations]]{{libheader|Scala}}<lang Scala>object ExceptionsTest extends App {
<lang Scala>object ExceptionsTest extends App {
class U0 extends Exception
class U0 extends Exception
class U1 extends Exception
class U1 extends Exception
Line 2,084: Line 2,127:
foo
foo
}
}
</lang>
</lang>Exception U0 is caught, exception U1 is caught and re-thrown. Program execution is terminated as the U1 exception is not caught when thrown the second time.
Exception U0 is caught, exception U1 is caught and re-thrown.
Program execution is terminated as the U1 exception is not caught
when thrown the second time.


=={{header|Seed7}}==
=={{header|Seed7}}==
When an [http://seed7.sourceforge.net/manual/errors.htm#Exceptions exception] is not [http://seed7.sourceforge.net/manual/errors.htm#Handlers handled]
When an [http://seed7.sourceforge.net/manual/errors.htm#Exceptions exception]
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.
the program is terminated and a [http://seed7.sourceforge.net/manual/errors.htm#Stack_trace stack trace] is written.
<lang seed7>$ include "seed7_05.s7i";
<lang seed7>$ include "seed7_05.s7i";
Line 2,142: Line 2,189:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}functional code, not class based, using blocks as functions, and anonymous exceptions (signals):
{{works with|Smalltalk/X}}functional code, not class based,
using blocks as functions, and anonymous exceptions (signals):
<lang Smalltalk>| u0 u1 foo bar baz|
<lang Smalltalk>| u0 u1 foo bar baz|


Line 2,173: Line 2,221:


foo value</lang>
foo value</lang>
"traditional" implementation, using class based exceptions, and method invocations:
"traditional" implementation, using class based exceptions,
and method invocations:
<lang Smalltalk>Exception
<lang Smalltalk>Exception
subclass: #U0
subclass: #U0
Line 2,248: Line 2,297:
foo
foo
foo</lang>
foo</lang>
{{out}}
Running this program results in:
<pre>$ tclsh85 exceptions.tcl
<pre>$ tclsh85 exceptions.tcl
caught exception U0
caught exception U0
Line 2,293: Line 2,342:
@(foo)</lang>
@(foo)</lang>


Run:
{{out|Run}}
<pre>$ txr except.txr
<pre>$ txr except.txr
caught u0: text0
caught u0: text0
Line 2,302: Line 2,351:


=={{header|Ursala}}==
=={{header|Ursala}}==
Foo calls bar, and bar calls baz. Normal termination of bar is bypassed if
Foo calls bar, and bar calls baz. Normal termination of bar is bypassed
baz raises an exception. The exception is caught or not by foo.
if baz raises an exception.
The exception is caught or not by foo.
<lang Ursala>#import std
<lang Ursala>#import std


Line 2,325: Line 2,375:
Note that the definition of bar includes no conditional (?) or exception
Note that the definition of bar includes no conditional (?) or exception
handling operators, and is written without regard for any exceptions.
handling operators, and is written without regard for any exceptions.
Here is an example bash session.
Here is an example bash session:
<pre>
<pre>
$ echo "valid input" | foo
$ echo "valid input" | foo
Line 2,359: Line 2,409:
Exception thrown: U1(An Exception)
Exception thrown: U1(An Exception)
</pre>
</pre>
foo catches exception U0 and ignores it.
foo catches exception U0 and ignores it. It calls bar with the exception to throw. bar in turn calls baz with that exception, which it throws. A stack trace is printed when an uncaught exception bubbles up to the VM (which handles all catchable exceptions).
It calls bar with the exception to throw. bar in turn calls baz
{{omit from|C}}
with that exception, which it throws.
{{omit from|GUISS}}
A stack trace is printed when an uncaught exception bubbles up to the VM
{{omit from|M4}}
(which handles all catchable exceptions).
{{omit from|Retro}}