繁体   English   中英

Scala 中的 try-finally 问题

[英]Issue with try-finally in Scala

我有以下 Scala 代码:

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

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

对于Scala 2.13 :如果它是AutoClosable您可以使用Using来获取一些资源并自动release它而无需错误处理:

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包装您的阅读器创建,如果它落入创建中,您将在里面遇到FileNotFoundException Failure

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

我建议不要在 Scala 代码中使用try ... catch块。 在某些情况下它不是类型安全的,可能会导致不明显的结果,但是对于在旧的 Scala 版本中释放一些资源,只有使用try - finally才能做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM