E4122

E4122#

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

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

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

  • 调用一个抛出错误的函数来重新抛出错误。

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

警告

catch! 语法已被弃用。请使用 catch {e => raise e} 显式重新抛出错误。

错误示例#

  • 直接抛出错误:

    ///|
    priv suberror 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 {
      // Error: Function with error can only be used 
      // inside a function with error types in its signature
      fail("throwing")
    }
    
  • 使用 catch! 捕获所有错误:

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

建议#

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

///|
suberror ArithmeticError {
  DivisionByZero
}

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

///|
pub fn rethrow() -> Unit raise {
  ...
}

///|
pub fn catch_all() -> Double raise {
  ...
}

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

///|
pub fn checked_div_noraise(a : Double, b : Double) -> Double noraise {
  try {
    if b == 0.0 {
      raise DivisionByZero
    }
    return a / b
  } catch {
    DivisionByZero => @double.not_a_number
  }
}