Similar to JAVA and other languages can I throw Exceptions and errors?
EDIT: Since SDK 1.15 and Daml-LF 1.14, Daml now provides native exception handling. Take a look at the documentation for details and examples.
Original Answer:
DAML does not have exceptions in the way they exist in Java. You can abort a transaction by calling abort
(or in some other ways, e.g., error
, division by zero, …). But it is not possible to catch that inside of DAML in any way or handle it. If you have errors that you want to handle then you can use the Either a b
type, e.g., Either String b
if you just want strings as error messages. An error is then represented using Left "this is an error"
while a non-error result is just wrapped in Right result
. In that case you can handle the error using pattern matching, e.g.,
case resultOrError : Either[String, Int] of
Left _ -> 42 -- if we got an error, we return 42
Right r -> r -- if we got no error we just return the result
Either
is the canonical way to pass errors around that shall be handled later. Outside of an Update
context, they can be used with do
notation and therefore appear like exceptions. Inside an Update
expression, you may want to define an EitherT
monad transformer such that you don’t have to explicitly fiddle with error handling in every step of the update.
Note however that a Left
inside an Update
does not abort the current update and undo the accumulated updates. For example,
do
archive cid1
x <- fetch cid2
if (someCondition x) then pure () else LeftT "error"
...
the transaction will archive cid1
even if the someCondition x
fails. This is similar to exceptions in languages like Java, where all side effects of the code before the exception remain. This makes reasoning about the code much harder. Very often, you would want to compose update expressions such that they all fail if only one of them raises an error. But this is not possible right now as it conflicts with the DAML privacy model.