How to use `raises`

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?
3 Replies
Jack Clayton
Jack Clayton14mo ago
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()
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()
Moosems / Three chickens
What happens if they fail? Just a normal error? Is this essentially just a way to say one is aware that the code may not work?
Jack Clayton
Jack Clayton14mo ago
Yeah application will throw an error, you can experiment and force errors. Modern language users expect to know if a function could potentially raise an error, and have the compiler warn them they're not handling it the potential for an error correctly.
Want results from more Discord servers?
Add your server