try
An expression whose failure becomes an absent value. try(expr) gives some(v) when expr
succeeds. It gives none where expr would otherwise stop the program.
const range_m: int32 = 8000;
const sweeps: int32 = 0;
const per_sweep: Optional<int32> = try(range_m / sweeps);Failures
try takes exactly one argument, and for an argument of type T the result is Optional<T>.
- Applying it to an expression that cannot fail is legal, and always gives
some. - It catches these failures: division and modulo by zero, an out-of-bounds index,
laston an empty array, out-of-rangesubstringindices, arangestep of0, and a failedassert. - It catches nothing the checker reports. A type error is not a failure a running program can reach.
const bearings_deg: int32[] = [10, 45, 90];
try((100: int32) / (0: int32)) // => none
try((100: int32) % (0: int32)) // => none
try(bearings_deg[(9: uint32)]) // => none
try(last([]: int32[])) // => none
try(substring("inbound", 0, 9)) // => none
try(bearings_deg[(1: uint32)]) // => some(45)There Are No Exceptions
Flex has no throw, no handler, and no error value: a failure is either something the checker rejects
or one of the runtime failures this page lists. try is the only form that observes one, and an absent
value is the only outcome it produces.
What is not a failure
Some things that look like failures are ordinary results, so try returns some of them.
- Out-of-domain float math gives the IEEE-754
NaNvalue.sqrtof a negative number, andasinoracosoutside[-1.0, 1.0], aresome(NaN). - An out-of-bounds slice clamps to the array and can only come back empty, never absent. Only a plain index fails.
const bearings_deg: int32[] = [10, 45, 90];
try(sqrt((-1.0: float64))) // => some(NaN)
try(asin((2.0: float64))) // => some(NaN)
try(bearings_deg[(1: uint32)..(9: uint32)]) // => some([45, 90])
try(bearings_deg[(8: uint32)..(9: uint32)]) // => some([])Errors
Using the result where the plain value is expected
try changes the type of the expression it wraps, so something has to open the optional.
const per_sweep: int32 = try((100: int32) / (2: int32)); // error: type-mismatchRelated
- optional — the type
tryproduces, and how to read it back. - match — the form that handles both outcomes.
- block, let, assert — the assertion
tryturns intonone.