scala - Scala中的try-finally问题
问题描述
我有以下scala代码:
val file = new FileReader("myfile.txt")
try {
// do operations on file
} finally {
file.close() // close the file
}
如何处理读取文件时抛出的 FileNotFoundException?如果我将该行放在 try 块中,我最终将无法访问里面的文件变量。
解决方案
对于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
。
推荐阅读
- neural-network - LSTM 预测的相对变化与缩放绝对值
- cypress - Cypress .intercept() 在 CircleCI 中不工作,在本地工作
- haskell - 使用提升的数据构造函数作为幻像参数
- python-3.x - VS Code Ubuntu 20.04 中的 Numpy
- python - 在 TKinter 中显示倒数计时器,同时使代码 BLOCKING 但不冻结 GUI
- sql - 计算每个月的活跃客户数量 (SQL)
- angularjs - 为什么我的 ngResource 'POST' 和 'DELETE' 中的参数不同?
- python - 如何向 Url urllib 发送正确的请求
- rsync - 对传递的文件使用 rsync
- javascript - 使用 websocket 发送 blob