ref: c818e95dc18d91228358fc9750d29dcd8cc9b488
parent: ce87687bbc9586ae0ecb1ea646596a76410ef568
author: henesy <henesy.dev@gmail.com>
date: Mon Mar 11 19:22:22 EDT 2019
add exceptions example and explanation
--- a/Exceptions/README.md
+++ b/Exceptions/README.md
@@ -6,14 +6,39 @@
## Source
-###
+### exceptions.b:17,26
+This section calculates numbers within the fibonacci sequence to a given interval. In this case, the first 5 numbers are calculated within the sequence.
+Note the call to the `raise` keyword after the fibonacci calculations have completed, but before the program exits.
-## Demo
+### exceptions.b:31,47
+The `fibonacci()` function attempts to perform a `fib()` call and, if an exception `e` is thrown, attempts to handle the exception in a manner depending on the exception type.
+Note that the attempted operation is wrapped in a `{ ... }` block.
+### exceptions.b:49,63
+
+The `raises` clause allows for warnings to be generated for un-caught exception potential within a program. Note that these exception types can be user-defined.
+
+The `FIB` exception type is defined at: exceptions.b:12
+
+## Demo
+
+ ; limbo exceptions.b
+ ; exceptions
+ F(0) = 1
+ F(1) = 1
+ F(2) = 2
+ F(3) = 3
+ F(4) = 5
+ sh: 798 "Exceptions":going down!
+ ;
+
## Exercises
--
+- Try removing the raise for "going down!".
+- Remove the `i < 5` portion of the for loop, how many values are printed and why?
+- Try removing the exception-catching block from around calls to `fib()`, do you get warnings?
+- Try changing the raise type within `fib()`, does `fibonacci()` handle the exception `e` differently?
--- a/Exceptions/exceptions.b
+++ b/Exceptions/exceptions.b
@@ -4,18 +4,60 @@
include "draw.m";
sys: Sys;
-print: import sys;
Exceptions: module {
init: fn(nil: ref Draw->Context, nil: list of string);
};
+FIB: exception(int, int);
+
init(nil: ref Draw->Context, nil: list of string) {
sys = load Sys Sys->PATH;
-
+ for(i := 0; i < 5 ; i++) {
+ f := fibonacci(i);
+ if(f < 0)
+ break;
+
+ sys->print("F(%d) = %d\n", i, f);
+ }
+
raise "going down!";
exit;
+}
+
+fibonacci(n: int): int {
+ {
+ fib(1, n, 1, 1);
+ } exception e {
+ FIB =>
+ (x, nil) := e;
+ return x;
+
+ "*" =>
+ sys->print("unexpected string exception %s raised\n", e);
+
+ * =>
+ sys->print("unexpected exception raised\n");
+ }
+
+ return 0;
+}
+
+fib(n, m, x, y: int) raises (FIB) {
+ if(n >= m)
+ raise FIB(x, y);
+ {
+ fib(n+1, m, x, y);
+ } exception e {
+ FIB =>
+ (x, y) = e;
+
+ x = x+y;
+ y = x-y;
+
+ raise FIB(x, y);
+ }
}
--- a/README.md
+++ b/README.md
@@ -38,6 +38,7 @@
- [Functions](./Functions)
- [Function References](./Function-Refs)
- [Generics, Picks, and Interfaces (kind of)](./Generics)
+- [Exceptions](./Exceptions)
## References