如何使用(使用source.fromfile)并处理错误
这是 https://stackoverflow.com/a/55440851/2691976
我有以下代码
import scala.io.Source
import scala.util.Using
object Problem {
def main(args: Array[String]): Unit = {
Using(Source.fromFile("thisfileexists.txt")) { source =>
println(1 / 1)
println(1 / 0)
}
}
}
运行 以下代码,它使用scala3,它将仅打印出1条线,没有错误。
scala3 test.scala
1
我期望有以下错误的错误,
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Problem$.main(test.scala:10)
at Problem.main(test.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at dotty.tools.scripting.ScriptingDriver.compileAndRun(ScriptingDriver.scala:42)
at dotty.tools.scripting.Main$.main(Main.scala:43)
at dotty.tools.MainGenericRunner$.run$1(MainGenericRunner.scala:230)
at dotty.tools.MainGenericRunner$.main(MainGenericRunner.scala:239)
at dotty.tools.MainGenericRunner.main(MainGenericRunner.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at coursier.bootstrap.launcher.a.a(Unknown Source)
at coursier.bootstrap.launcher.Launcher.main(Unknown Source)
那么当我使用使用
时,为什么它不会打印出错误(我怀疑它在这里引起问题)呢?
解决方案是什么,因此我可以使用和 source.fromfile
使用潜在错误使用?
我已经阅读了使用
scala 2 doc and scala 3 doc 3 doc <
以防这很重要,我正在使用Mac
scala3 --version
Scala code runner version 3.1.2-RC1-bin-20211213-8e1054e-NIGHTLY-git-8e1054e -- Copyright 2002-2021, LAMP/EPFL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是因为
使用
返回尝试
,您可以在此处看到https://www.scala-lang.org/ api/2.13.x/scala/util/使用$ .html#apply [r,a](资源:=%3ER)(f:r =%3EA)(remiteVidence $ 1:scala.util.util.using.usis.usis.user.releasable [r] ):scala.util.try [a]
您可以使用
.fold
,.get
,模式匹配等。例如:
或如下:
您可以在Scala中阅读有关尝试的更多信息:
Thats because
Using
returnsTry
as you can see herehttps://www.scala-lang.org/api/2.13.x/scala/util/Using$.html#apply[R,A](resource:=%3ER)(f:R=%3EA)(implicitevidence$1:scala.util.Using.Releasable[R]):scala.util.Try[A]
You can use
.fold
,.get
, pattern matching, etc.for example:
or as follows:
You can read more about Try at scala:
https://www.scala-lang.org/api/2.13.x/scala/util/Try.html