The tour, 8 of 11
Errors
Throws, Try, Catch, and Finally for what can go wrong, and panics for bugs.
A Function that can fail says what it throws with Throws, and the compiler makes its callers
deal with it: catch it, pass it on with Try, or turn it into a Null with Try?.
Import std.core
Class NotEnoughGold Extends Error
End Class
Function Buy(gold: Int, price: Int): Int Throws NotEnoughGold
If gold < price Then Throw NotEnoughGold("costs {price}, you have {gold}")
Return gold - price
End Function
Try
Print("left: {Try Buy(100, 30)}")
Print("left: {Try Buy(20, 30)}")
Catch e As NotEnoughGold
Print("can't buy it: {e.Message}")
Finally
Print("the shop closes")
End Try
Print(Try? Buy(5, 10) ?? -1)Output
left: 70 can't buy it: costs 30, you have 20 the shop closes -1
Try f()givesf’s value, or throws its error on to the caller, which has to say itThrowsit too.Try? f()givesf’s value, orNullwhen it throws.Catch e As SomeErrorcatches that error and the ones extending it.- Top-level code can use
Trytoo: an error nothing catches ends the program, with where it was thrown.
Panics are bugs
An error is something that can happen to a working program: a missing file, a bad save. A
panic is a bug: an index out of range, overflow in a debug build, Null where it can’t be. It
stops the program, with exit code 101 and a stack trace of FutureBlitz’s own names, files, and
lines, in release builds too.
Import std.core
Function Third(items: Int[]): Int => items[2]
Print(Third([1, 2, 3]))
Print(Third([1, 2]))Output
3
panic: index 2 is out of range for 2 elements at main.fb:3:38
at Third (main.fb:3)
at top-level code (main.fb:6)Assert(condition) panics when what it says isn’t so. Next:
Interfaces and generics.
Report an issue with this page or with FutureBlitz on GitHub.