首页 > 解决方案 > Scala中的try-finally问题

问题描述

我有以下scala代码:

val file = new FileReader("myfile.txt")
try {
 // do operations on file
} finally {
  file.close() // close the file
}

如何处理读取文件时抛出的 FileNotFoundException?如果我将该行放在 try 块中,我最终将无法访问里面的文件变量。

标签: scalaexception

解决方案


对于scala 2.13:您可以只使用Using来获取一些资源,并且release如果它是一个,它会自动没有错误处理AutoClosable

import java.io.FileReader
import scala.util.Using

val newStyle: Try[String] = Using(new FileReader("myfile.txt")) { 
  reader: FileReader =>
    // do something with reader
    "something"
}
newStyle
// will be 
// Failure(java.io.FileNotFoundException: myfile.txt (No such file or directory))
// if file is not found or Success with some value it will not fall

斯卡拉 2.12

您可以将您的阅读器创作包装起来scala.util.Try,如果它落在创作上,您将得到Failure内部FileNotFoundException

import java.io.FileReader
import scala.util.Try

val oldStyle: Try[String] = Try{
  val file = new FileReader("myfile.txt")
  try {
    // do operations on file
    "something"
  } finally {
    file.close() // close the file
  }
}
oldStyle
// will be 
// Failure(java.io.FileNotFoundException: myfile.txt (No such file or directory))
// or Success with your result of file reading inside

我建议不要try ... catch在 scala 代码中使用块。在某些情况下,它不是类型安全的,并且可能导致不明显的结果,但是要在旧的 scala 版本中释放一些资源,唯一的方法就是使用try- finally


推荐阅读