Exceptions: Difference between revisions

Content added Content deleted
m (→‎{{header|Raku}}: Fix link and commet: Perl 6 --> Raku)
(Added Wren)
Line 3,396: Line 3,396:
End Try
End Try
End Sub</lang>
End Sub</lang>

=={{header|Wren}}==
Wren doesn't have exceptions as such but we can simulate them by trying to run code which may cause an error in a fiber and then capturing any error that does occur.

Errors can be thrown by calling the Fiber.abort method. The VM will also call this method automatically if a runtime error occurs such as attempting to call a function that doesn't exist.

Here's an example of all this.
<lang ecmascript>var intDiv = Fn.new { |a, b|
if (!(a is Num && a.isInteger) || !(b is Num && b.isInteger)) Fiber.abort("Invalid argument(s).")
if (b == 0) Fiber.abort("Division by zero error.")
if (a == 0) a = a.badMethod()
return (a/b).truncate
}

var a = [ [6, 2], [6, 0], [10, 5], [true, false], [0, 2] ]
for (e in a) {
var d
var f = Fiber.new { d = intDiv.call(e[0], e[1]) }
f.try()
if (f.error) {
System.print("Caught %(f.error)")
} else {
System.print("%(e[0]) / %(e[1]) = %(d)")
}
}</lang>

{{out}}
<pre>
6 / 2 = 3
Caught Division by zero error.
10 / 5 = 2
Caught Invalid argument(s).
Caught Num does not implement 'badMethod()'.
</pre>


=={{header|zkl}}==
=={{header|zkl}}==