Essential Error Handling
In this section we will go over the essential information about Optionals and safe methods for working with them, for example
if (catch optional_value)
and the Rethrow operator !
.
In the advanced section there are other nice to have features.
Like an alternative to safely unwrap a result from an Optionals using
if (try optional_value)
and an unsafe method to force unwrap !!
a result from an Optional, return default values for optionals ??
if they are empty and other more specialised concepts.
What is an Optional?
Optionals are a safer alternative to returning -1
or null
from
a function, when a valid value canβt be returned. An Optional
has either a result or is empty. When an Optional
is empty it has an Excuse
explaining what happened.
- For example trying to open a missing file returns the
Excuse
ofIoError.FILE_NOT_FOUND
. - Optionals are declared by adding
!
after the type. - An
Excuse
is of the typeanyfault
.
The Optional Excuse is set with ?
after the value.
π Unwrapping an Optional
Checking if an Optional is empty
Automatically unwrapping an Optional result
If we escape the current scope from an if (catch my_var)
using a return
, break
, continue
or Rethrow !
,
then the variable is automatically unwrapped to a non-Optional:
Using the Rethrow operator !
to unwrap an Optional value
- The Rethrow operator
!
will return from the function with theExcuse
if the Optional result is empty. - The resulting value will be unwrapped to a non-Optional.
β οΈ Optionals affect types and control flow
Optionals in expressions produce Optionals
Use an Optional anywhere in an expression the resulting expression will be an Optional too.
Optionals affect function return types
Functions conditionally run when called with Optional arguments
When calling a function with an Optionals as arguments, the result will be the first Excuse found looking left-to-right. The function is only executed if all Optional arguments have a result.
Interfacing with C
For C the interface to C3:
- The
Excuse
in the Optional of typeanyfault
is returned as the regular return. - The result in the Optional is passed by reference.
For example:
The c3fault_t
is guaranteed to be a pointer sized value.