#How to use `raises`

1 messages · Page 1 of 1 (latest)

candid lance
#

What does the raises keyword do for error handling, how do I use it, and what does it returns if the function fails? All I could in the docs was "Both support raising exceptions, but this must be explicitly declared on a fn with the raises keyword." If its for raising exceptions, how do I do this properly?

jovial drift
#
from python import Python

# Handle errors so caller doesn't need to
fn test1():
    try:
        let np = Python.import_module("numpy")
        print(np.array([1, 2, 3]))
    except e:
        print("Error importing and using numpy:", e.value)


# Doesn't handle errors, but caller will need to
fn test2() raises:
    let np = Python.import_module("numpy")
    print(np.array([1, 2, 3]))


# Doesn't need raises because `def` expects that it could raise
# Caller still needs to handle error
def test3():
    let np = Python.import_module("numpy")
    print(np.array([1, 2, 3]))


fn main():
    let a = test1()
    # These two will cause an error unless you put them in try/catch blocks or change `fn main()` to raises
    let b = test2()
    let c = test3()
candid lance
#

What happens if they fail? Just a normal error?

candid lance
#

Is this essentially just a way to say one is aware that the code may not work?