βοΈTry-Statements
Try-statement syntax
try <expr> with <expr if error != nil>
--OR--
let <successVar, failureVar> = try <expr> with <expr>
The try-statement will evaluate the expression in-between try
and with
. Said expression must have a type of (..., error)
.
If
error != nil
: the expression to the right ofwith
will be returned.If
error == nil
:If you're using the first syntax: Control flow will continue as normal
If you're using the second syntax: expression between
try
andwith
will be destructured intosuccessVar
andfailureVar
Working Example
package main
import "fmt" as fmt
import "errors" as errors
fun divide(num1: Int, num2: Int): (Int, Error) {
if num2 == 0 {
return (0, errors.new("Cannot divide by 0"))
}
return (num1 / num2, null)
}
fun divideBy2(num: Int): (Int, Error) {
return divide(num, 2)
}
fun divideBy0(num: Int): (Int, Error) {
return divide(num, 0)
}
fun getResults(num: Int): (Int, Error) {
let dBy2Res, dBy2Err = try divideBy2(5) with (dBy2Res, dBy2Err)
let dBy0Res, dBy0Err = try divideBy0(10) with (dBy0Res, dBy0Err)
return (dBy2Res + dBy0Res, null)
}
fun main(): Unit {
fmt.println("Let's see if there's an error:")
let res, err = getResults(10)
fmt.println(err != null)
}
Last updated