Gauntlet Documentation
  • 🏠Welcome
  • πŸ…Getting Started
    • 🧠Introduction To Gauntlet
  • ‼️Read before Proceeding
  • ⬇️Installation
  • πŸ‘¨β€πŸ’»VSCode Extension
  • πŸ“šBasics
    • πŸ’¨Running Gauntlet
    • πŸ“„File Setup & Hello World
  • πŸ” Scope Variables
  • πŸ–ΌοΈConstants
  • 🧩Functions
  • ↔️If Statements
  • πŸ”‘Ternary Operator
  • πŸ’ Switch-Case
  • πŸ“©Select-Case
  • ➰Loops
  • πŸ“Structs
  • 🧱Interfaces
  • πŸͺͺAliases
  • πŸ“ŽMethods
  • πŸ¦™Lambdas
  • πŸ•ΈοΈMiscellaneous
  • ⚑Advanced Features
    • πŸ”€When-Cases
    • 🚰Pipes
    • ⁉️Try-Statements
    • 🎭Force-Statements
    • 🌯Wrapper Types
Powered by GitBook
On this page
  • Try-statement syntax
  • Working Example
Export as PDF
  1. Advanced Features

Try-Statements

Try-statement syntax

try <expr> with <expr if error != nil>

--OR--

let <successVar, failureVar> = try <expr> with <expr if error != nil>

The try-statement will evaluate the expression in-between try and with. Said expression must have a type of (..., error).

  • If error != nil: the expression to the right of with will be returned.

  • If error == nil:

    • If you're using the first syntax: Control flow will continue as normal

    • If you're using the second syntax: expression between try and with will be destructured into successVar and failureVar

Working Example

package main

import "fmt" as fmt
import "errors" as errors

fun (Int, Error) divide(Int num1, Int num2) {
  if num2 == 0 {
    return (0, errors.new("Cannot divide by 0"))
  }
  return (num1 / num2, null)
}

fun (Int, Error) divideBy2(Int num) {
  return divide(num, 2)
}

fun (Int, Error) divideBy0(Int num) {
  return divide(num, 0) 
}

fun (Int, Error) getResults(Int num) {
  let dBy2Res, dBy2Err = try divideBy2(5) with (dBy2Res, dBy2Err)
  let dBy0Res, dBy0Err = try divideBy0(10) with (dBy0Res, dBy0Err)
  return (dBy2Res + dBy0Res, null)
}

fun Unit main() {
  fmt.println("Let's see if there's an error:")
  let res, err = getResults(10)
  fmt.println(err != null)
}
package main

import fmt "fmt"
import errors "errors"

func divide(num1 int, num2 int) (int, error) {
	if num2 == 0 {

		return 0, errors.New("Cannot divide by 0")
	}

	return num1 / num2, nil

}

func divideBy2(num int) (int, error) {

	return divide(num, 2)

}

func divideBy0(num int) (int, error) {

	return divide(num, 0)

}

func getResults(num int) (int, error) {
	dBy2Res, dBy2Err := divideBy2(5)
	if dBy2Err != nil {
		return dBy2Res, dBy2Err
	}
	dBy0Res, dBy0Err := divideBy0(10)
	if dBy0Err != nil {
		return dBy0Res, dBy0Err
	}

	// Eliminates any 'unused variable' errors
	_, _, _, _ = dBy0Err, dBy0Res, dBy2Err, dBy2Res
	return dBy2Res + dBy0Res, nil

}

func main() {
	fmt.Println("Let's see if there's an error:")
	res, err := getResults(10)
	fmt.Println(err != nil)
	// Eliminates any 'unused variable' errors
	_, _ = err, res

}
Let's see if there's an error:
true
PreviousPipesNextForce-Statements

Last updated 8 days ago

⚑
⁉️