Errors
Draft uses explicit error handling with Result and Option types. No exceptions.
Result Type
Section titled “Result Type”Result<T, E> represents either success (ok) or failure (err):
enum Result<T, E> ok(value: T) err(error: E)fin enum.Returning Errors
Section titled “Returning Errors”action divide(@a: Float, @b: Float) -> Result<Float, String> if @b == 0.0 return err("Division by zero") fin if. return ok(@a / @b)fin action.Handling Results
Section titled “Handling Results”Match Expression
Section titled “Match Expression”@result = divide(10.0, 2.0)match @result when ok then write("Result: " + string(@result#value)) when err then write("Error: " + @result#error)fin match.Unwrap
Section titled “Unwrap”Get the value or panic:
@value = divide(10.0, 2.0)#unwrap()Unwrap or Default
Section titled “Unwrap or Default”@value = divide(10.0, 0.0)#unwrap_or(0.0)Error Propagation
Section titled “Error Propagation”Use ? to propagate errors:
action process() -> Result<Void, Error> @data = read_file("data.json")? @// Returns early on error @parsed = parse(@data)? save(@parsed)? return ok(nothing)fin action.Custom Error Types
Section titled “Custom Error Types”record Error message: String code: Intfin record.
action fail() -> Result<Void, Error> return err(Error { message: "Something went wrong", code: 500 })fin action.Option Type
Section titled “Option Type”Option<T> represents a value that may or may not exist:
enum Option<T> some(value: T) nonefin enum.Returning Options
Section titled “Returning Options”action find_user(@id: Int) -> Option<User> if @id < 0 return none fin if. return some(User { id: @id, name: "Alice" })fin action.Handling Options
Section titled “Handling Options”@user = find_user(1)match @user when some then write(@user#value#name) when none then write("User not found")fin match.For unrecoverable errors:
action critical() if @something_went_wrong panic("Unrecoverable error!") fin if.fin action.Assert
Section titled “Assert”Check conditions in debug builds:
assert @value > 0assert @result != nil, "Result should not be nil"No Null Pointers
Section titled “No Null Pointers”Draft eliminates null pointer exceptions. Use Option instead:
@maybe: Option<String> = none
action find(@id: Int) -> Option<User> return nonefin action.Next Steps
Section titled “Next Steps”Continue to Async for asynchronous programming.
