类型单位的Scala表达式无法确认是否键入String

이국화*_*이국화 2 error-handling scala try-catch

try{
    throwsException();
} catch {
    case e: IOException => println("IO Exception");
} finally {
    println("this code is always executed");
}
Run Code Online (Sandbox Code Playgroud)

在此 catch 部分中,它始终弹出“类型单元的表达式未确认键入字符串”错误。

Sar*_*ngh 5

看起来这段代码是一个较大块的一部分,应该将其评估为String。例如,我们可以考虑以下内容:

def getStringResult(): String = {
  try{
    throwsException();
  } catch {
    case e: IOException => println("IO Exception");
  } finally {
   println("this code is always executed");
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以看到,如果发生异常,则提供{ case e: IOException => println("IO Exception") }了type的部分函数IOException => Unit。这导致类型不匹配。

您可以按照以下方法解决此问题,

def getStringResult(): String = {
  try{
    throwsException();
  } catch {
    case e: IOException => "IOException String"
  }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以做一个更像Scala的方法,

def getStringResult(): String = {
  val resultTry = Try(throwsException())
  // resultTry will be of type Try[String]

  resultTry.getOrElse("String in case of exception")
}
Run Code Online (Sandbox Code Playgroud)