try.fz
# This file is part of the Fuzion language implementation.
#
# The Fuzion language implementation is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, version 3 of the License.
#
# The Fuzion language implementation is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License along with The
# Fuzion language implementation. If not, see <https://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------
#
# Tokiwa Software GmbH, Germany
#
# Source code of Fuzion standard library feature try
#
# Author: Fridtjof Siebert (siebert@tokiwa.software)
#
# -----------------------------------------------------------------------
# try -- simple exception effect
#
# try provides an operation 'cause' that immediately stops execution and
# returns an 'error' wrapped in an 'outcome'.
#
public try (# type parameter used only to distinguish different
# instances of `try`. This permits using, e.g.,
# `try reader` and `try writer` and distinguish the
# errors raised by the reader from those raised
# by the writer.
#
public T type,
h error->void,
_, _ unit
) : eff.fallible error h
is
# type feature that to create an instance of `try` with the given error handler.
#
public fixed redef type.new(h error->void) =>
try T h unit unit
# install this effect and execute 'f'. Wrap the result of 'f' into an
# 'outcome' if 'f' returns normally, otherwise if 'f' is aborted early
# via a call to 'raise' wrap the 'error' passed to 'raise' into the
# resulting 'outcome'.
#
public type.on(R type, f ()->R) outcome R =>
try.this.type.try (outcome R) ()->
f()
.catch e->
e
# terminate immediately with the given error wrapped in 'option'.
#
public raise(e error) => cause e
# convenience routine to create a new instance of 'try T' and run 'f' in
# it. The result will be an `outcome R` that, in case of success, contains
# the result of `f`, or, in case of `(try T).env.raise`, contains the error.
#
public try(T type,
R type,
f ()->R) =>
(try T).on f
# convenience routine to create a new instance of 'try T' and run 'f' in
# it. Return the result of 'f' directly or panic in case 'f' calls
# '(try T).env.raise'.
#
public try_or_panic(T type,
R type,
f ()->R) R =>
match (try T).on f
e error => panic $e
r R => r
last changed: 2025-01-23