如何 "override" 在 Scala 中抛出异常?

How to "override" an exception in scala?

所以我有一个方法,它已经有一个抛出 ExceptionA 的 try 块。现在我需要在调用此方法的地方放置另一个 try 块,并且需要抛出带有一些附加细节的异常。像这样:

method inner():
    try{
    //some logic
    } catch {
    throw new ExceptionA("exceptionA occurred")
    }

method outer():
    identifier = fromSomeDBCallPrivateToOuter()
    try{
    inner()
    } catch {
    // now either 
    // throw new Exception("Error with identifier" + identifier)
    // or
    // append identifier to thrown error from inner() 
    }

有人可以就如何在 Scala 中执行此操作提供任何见解或建议吗?提前致谢!

您的代码片段中的内容将按照编写的方式工作(如果您更正语法),但需要注意的是,异常是不可变的(即使它们不是,改变它们仍然不是一个好主意),因此,您需要创建一个新的,而不是“附加”到异常,并将原始设置为 cause.

尽管使用 Try monad 而不是“程序”try/catch 块,但在 scala 中更为惯用。像这样:

     case class ExceptionB(id: String, original: ExceptionA) 
         extends Exception(s"Badness happened with id $id", original)
     def outer(): Try[ReturnType] = 
       val id = getId()
       Try {
         inner 
       } recover { 
         case e: ExceptionA if iWannaNewException => throw new Exception(s"Id: id")
         case e: ExceptionA => throw ExceptionB(id, e)
      }

您也可以使用Either structure。如果函数完成没有错误或 Left(message) 包含有关错误的信息,则此结构可以 return Right(value)。您可以像下面这样调整您的代码:

def inner(): Either[String, Int] = {
  if (checkSomeStuff()) Left("Cannot assigne identifier")
  else Right(doSomeStuff())
}

def outer(): Either[String, Int] = {
  inner() match {
    case Left(error)  => {
      println("There is an error: " + error) 
     // you can also throw new Exception(s"Some info about $error") here
    }
    case Right(identifier) => {
      println("Identifier : " + identifier) 
      doSomeStuffWithId()  // do some staff for id
    }
  }
}

如果您想使用异常,您需要选择谁来处理错误情况(在 innerouter 函数中)。