Exceptions
Exceptions signal failures during execution. When thrown, execution stops immediately and the error is returned to the caller.
Throwing Exceptions
Throw a String
endpoint Withdraw(amount U64):
if amount > balance:
throw "Insufficient balance"
Throw with Class
A class that implements __str__ can be thrown. The method's result is the error message, and the
class name becomes the error type:
class Person:
field age U64
method __str__() -> (err String):
err = f"Underage: only {self.age} years"
endpoint VerifyAge(age U64):
memory person = Person{age: age}
if person.age < 18:
throw person // Calls __str__ automatically
In a test this reports !Person::Underage: only 10 years, so callers can tell error classes apart
without parsing the message. revert works the same way.
A class without __str__ fails with Person does not implement __str__. Defining __except__
doesn't help, because neither throw nor revert calls it.
Use Cases
Use exceptions for:
- Invariant violations — conditions that should never occur
- Permission checks — unauthorized access attempts
- Validation failures — invalid input data
Don't use exceptions for control flow. They immediately halt execution.
Can I catch exceptions in Coco?
try, catch, and finally are reserved keywords for future use. Exception handling is not yet implemented.
Error Types
When testing, errors appear in the format !<error_type>::<error_message>:
| Error Type | When It Occurs |
|---|---|
builtin.AccessError | Map key doesn't exist, index out of bounds |
builtin.ArithmeticError | Integer overflow/underflow |
builtin.RuntimeError | General runtime errors |
builtin.NotImplemented | A class doesn't define the special method an operator needs |
builtin.MeterExhausted | The call ran out of fuel |
user | From throw "message" |
The class name, such as Person | From throw of a class instance |