E4120

E4120#

应用可能会引发错误,但没有处理。请在应用中添加一个中缀运算符 !?

在 MoonBit 中,我们要求程序员明确标注哪些函数可能引发错误。这是通过在函数应用中添加中缀运算符 !? 来完成的。运算符 ! 用于重新引发错误,运算符 ? 用于将错误物化为 Result[T, E] 类型。

错误示例#

fn may_raise_error(input : Int) -> Unit! {
  if input == 42 {
    return
  }
  fail!("failed")
}

fn main {
  may_raise_error(42)
  // Error: The application might raise errors of type Error, but it's not handled.
  // Try adding a infix operator `!` or `?` to the application, so that it looks like `...!(...)` or `...?(...)`.
}

建议#

您可以重新引发错误:

fn main {
  try {
    may_raise_error!(42)
  } catch {
    error => println("Error: \{error}")
  }
}

或者将错误物化为 Result[T, E] 类型:

fn main {
  let result = may_raise_error?(42)
  println("Result: \{result}")
}