E4122#
Invalid raise operation. Can only be used inside a function with error types in its signature.
There are 3 raise operations in MoonBit, and they must be used inside a function with error types in its signature or a try block.
Use the
raise
keyword to raise an error directly.Re-raise an error by annotating the function application with the
!
operator.Explicitly handle the error using the
try ... catch! ...
block. Thecatch!
means re-raise all the errors that are not handled in the catch block.
Erroneous example#
Raise the error directly:
type! ArithmeticError {
DivisionByZero
}
pub fn checked_div(a : Double, b : Double) -> Double {
if b == 0.0 {
raise DivisionByZero // Error: raise can only be used inside ...
}
return a / b
}
Re-raise the error:
pub fn rethrow() -> Unit {
fail!("throwing") // Error: `!` operator will rethrow the error raised in the function application, and can only be used inside ...
}
Catch all errors using catch!
:
pub fn catch_all() -> Double {
try {
fail!("Failed") // Error: catch! will rethrow unhandled error, and can only be used inside ...
} catch! {
}
}
Suggestion#
You can either modify the surrounding function to have error types in its signature:
pub fn checked_div(a : Double, b : Double) -> Double!ArithmeticError {
...
}
pub fn rethrow() -> Unit! {
...
}
pub fn catch_all() -> Double! {
...
}
Or use the try ... catch ...
block to handle the error:
pub fn checked_div(a : Double, b : Double) -> Double {
try {
if b == 0.0 {
raise DivisionByZero // Error: raise can only be used inside ...
}
return a / b
} catch {
_ => {
println("DivisionByZero")
@double.not_a_number
}
}
}