Would it be a good idea to use Failure and FailureQ in own code
What I personally usually do is to still use $Failed
/ exceptions when a returned $Failed
/ thrown exception can't be used constructively when handled / caught, other than issuing the right message. In some cases, however, the application logic requires to do more than that. In particular, certain data associated with the state right before the failure may be needed to handle the error correctly. In cases like that, Failure
seems a good match.
There are at least two different modes in which Failure
can be used. One is that in the case of a failure, you return the Failure
object to the calling function, instead of just returning $Failed
. This would allow to return not just the fact of the failure, but also error code. Another is to use Throw
like
Throw[Failure[...], tag]
combining Failure
and exceptions. This is needed in the same situations where exceptions are typically used, but Failure
allows us to bring more information along with an exception. Along similar lines, Failure
can also be abused constructively to have a non-local control flow, even in cases which aren't hard failures - I did this a few times in inner functions not facing the user.
Surely one can place association inside an exception tag, doing essentially the same:
Throw[$Failed, error[label, assoc]]
or something like that, but I feel that using Failure
in cases like this is semantically cleaner.
All in all, I don't see any reason not to use Failure
in cases when one needs to bring additional information to the function that must handle the error, be it in return mode or exception mode.