Anonymous user
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 15:17, 26 April 2018
, 6 years agoUpdate Smalltalk example (remove box about being incomplete)
(→{{header|Smalltalk}}: Incomplete) |
(Update Smalltalk example (remove box about being incomplete)) |
||
Line 2,675:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<lang smalltalk>
Exception subclass: #U0.
Exception subclass: #U1.
Object subclass: Foo [
foo
[2
[ "==>" [self bar]
on: U0
do:
[:sig |
'Call to bar was aborted by exception U0' printNl.
sig return]]]
bar
[bazCount := bazCount + 1.
bazCount = 1 ifTrue: [U0 new
bazCount = 2
"Thirds time's a
]
</lang>
Running the code:
<lang Smalltalk>
st> Foo new foo
'Call to bar was aborted by exception U0'
Object: Foo new "<-0x4c9a7960>" error: An exception has occurred
U1(Exception)>>signal (ExcHandling.st:254)
Foo>>baz (catch_exception.st:32)
Foo>>bar (catch_exception.st:27)
optimized [] in Foo>>foo (catch_exception.st:19)
BlockClosure>>on:do: (BlkClosure.st:193)
Foo>>foo (catch_exception.st:20)
UndefinedObject>>executeStatements (a String:1)
nil
</lang>
Explanation:<br/>
Inside the foo method, inside the 2 timesRepeat: block, there is a small
block <code>[self bar]</code> which simply calls bar. This block is sent
the <code>#on:do:</code> message, which will evaluate the block and catch
any mentioned exception. First time this block is evaluated, it results in
a U0 exception, which we catch and handle by printing a message and
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
(the following do: block) can do quite some cool stuff, like retrying the
block, retrying with a different block, and even resuming evaluation at the
point where the exception was raised (baz in this example) having <code>U0
new signal</code> return some value.
=={{header|Swift}}==
|