Skip to content

Result-based error handling & Traps #33

@Zffu

Description

@Zffu

result type

In order to properly handle errors, a result<V, E> type must be added

Contents of types:

  • Indicator bit bit (0: V present, 1: E present)
  • V object (potentially)
  • E object (potentially)

Size (stack allocated): 1 + max(size V, size E) bits
Size (heap allocated): 1 + (size V || size E) bits depending on indicator bit

? operator

The ? operator can be used within functions to automatically handle any function that returns a result. If said returned result is E (error based), we move to the trap

Trap

A trap is a feature allowing for uniform handling of errors in a given function. It defines what happens when the ? operator catches an error.

The default trap for any error type E is to return the error to propagate it

A function can have one trap for each error type E that the ? is used onto.

Furthermore, a function can posses a safety trap that catches any runtime safety violations without the need of the ? operator. The default safety trap is to crash the program with a safety violatio n error. Any safety trap is ignored if runtime optimizations are disabled. You need at least one possible safety violation before being able to define your own safety trap.

Furthermore, you can create a trap without any target E types that will catch any error types that do not have a specific trap (this include the safety faults trap)

Example Syntax:

func test(s32[] myArray) result<void, MyFirstErrorType> {
    var s32 myInt = myArray[797]; // Might cause safety violation

      var si32 result = myFunctionThatMightError(myInt)? // Assuming this returns a result<s32, E> and E = MyFirstErrorType for example, we can directly get the `s32` using the ? operator

   send_to_printer(myInt)?; // Assuming this returns a result<bool, IOErrorType>


   // We can now setup the traps

   trap safety(cstring err) {
       ret MyFirstErrorType.new(err); // Converts the raw cstring into a MyFirstErrorType we can actually return
   }

   trap(MyFirstErrorType err) {
       ret err; // This trap is automatically made for every E type the ? operator is used onto
   }


   // Handles IOError since it doesnt have a trap
   trap {
       ret MyFirstErrorType.new("Unknown error has happened!")
   }
}

   

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions