try catch. If an exception is not caught, the program terminates with errCode.
In TVM, exceptions are numbers. There is no Error class or exception hierarchy, only exit codes.
Error codes
A simple pattern is to define a constant for each exception that a contract may produce:enum — they are easier to maintain and reference, as enumerations come with exhaustive checks from the compiler:
throw and related statements described on this page.
Use error codes between 64 and 2048Lower values are reserved by TVM. Larger ones are more gas-expensive.
throw statement
To throw an exception unconditionally:
throw someVariable are supported but not recommended. It works, but the compiler cannot determine possible error codes and therefore cannot provide a correct ABI for external callers.
An exception can carry an argument:
catch and must be a TVM primitive, not a tuple nor a tensor.
assert statement
An assert is a shorthand for “throw if a condition is not satisfied”. It is commonly used when parsing user input:
- The long form
assert (condition) throw ERR_CODEis preferred. - The short form
assert (condition, ERR_CODE)exists but is not recommended.
condition must be either a boolean or an integer, where non-zero integers are treated as true and all other integer values as false.
An assert statement is equivalent to:
TVM implicit throws
During contract execution, TVM may throw runtime exceptions. For example:slice.loadInt(8)will fail when the slice is empty.builder.storeRef(cell)will fail when the builder has 4 references already.tuple.push(value)will fail when the tuple has 255 elements already.- etc.
catch block. It can only be prevented by writing exhaustive testing suites.
try catch statement
The catch block is used to handle most runtime errors within the try block, except for out-of-gas exceptions:
- Use the short form
catch { ... }whenerrCodeis not needed. - Use the long form
catch (errCode, arg)when the exception may carry an argument produced bythrow (errCode, arg). If the exception was thrown asthrow errCode, the argument isnull.
Any error inside a
try block reverts all changes made within. TVM restores local variables and control registers to the state they had before entering try.However, gas counters and TVM codepage settings are not rolled back. Gas is always spent.