E4122

E4122#

只能在具有错误类型签名的函数中抛出错误。

MoonBit 中有 3 个抛出错误操作,它们必须在具有错误类型签名的函数或 try 块中使用。

  • 使用 raise 关键字直接引发错误。

  • 使用 ! 运算符重新抛出错误。

  • 使用 try ... catch! ... 块显式处理错误。catch! 意味着重新抛出 catch 块中未处理的所有错误。

错误示例#

直接抛出错误:

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
}

重新抛出错误:

pub fn rethrow() -> Unit {
  fail!("throwing") // Error: `!` operator will rethrow the error raised in the function application, and can only be used inside ...
}

使用 catch! 捕获所有错误:

pub fn catch_all() -> Double {
  try {
    fail!("Failed") // Error: catch! will rethrow unhandled error, and can only be used inside ...
  } catch! {
  }
}

建议#

您可以修改周围的函数以在其签名中包含错误类型:

pub fn checked_div(a : Double, b : Double) -> Double!ArithmeticError {
  ...
}

pub fn rethrow() -> Unit! {
  ...
}

pub fn catch_all() -> Double! {
  ...
}

或者像使用 try...catch 块来处理错误:

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
    }
  }
}