ricardoboss / STEP

The STEP programming language
http://step-lang.dev/
MIT License
5 stars 1 forks source link

`throw` statements #98

Open ricardoboss opened 11 months ago

ricardoboss commented 11 months ago

Sometimes, programmers may want the ability to throw errors and handle them further up in the callstack or even forward the error to the user.

I'd not introduce types for this, so throw would accept anything as an argument.

Introducing a way to throw things might also require a way to catch things. So additionally, a try/catch statement might be needed as well.

Possible designs

The "classic":

try {
    throw "Nope"
} catch (string error) {
    println("Caught: ", error)
}

Using local "panic-calm-callback":

{
    calm = (string error) {
        println("Caught: ", error)
    }

    if (1 == 2) {
        // uses local "calm" function to handle the panic
        // also functions like a return, so no code after is executed
        panic "I broke math"
    } else {
        println("everything fine")
    }
}

// a panic outside of a code block without a global calm handler will trigger a runtime halt
panic "Don't know what to do"

Or like swift:

string contents
do {
    contents = try thisWillThrow(data)
} catch(string error) {
    contents = error
}

function thisWillThrow = () {
    throw "Told ya"
}

Or maybe functional:

string value = try(() {
    return thisWillThrow(data)
}, (string error) {
    println("caught error ", error)

    return "error"
})