Does Scala io.Source.FromFile return any kind of exception?
I was reviewing my code for the last time开发者_StackOverflow社区 searching for exceptions when I stopped on this line of code:
var list: Array[String] = Source.fromFile(this.Path).getLines.toArray
I searched in the documentation on scala-lang but it seems that none of the methods of that line throws any kind of ioException
...
How is that possible?
EDIT:
try {
var list: Array[String] = Source.fromFile("").getLines.toArray
}
catch {
case ex:Exception => println(ex.getMessage)
}
does not print anything, why?
Checked exceptions are enforced by the javac, the JVM don't really know about them. And contrary to Java, Scala doesn't care about checked exceptions.
Look at Source for instance, you won't notice any code dealing with exceptions. Something that is impossible in good old Java, which would require try
/catch
s or throws
clauses.
Despite that, a Scala library author may still want to make sure that Java users check for these exceptions, so there is the @throws annotation, which let you declare that a method may throw a exception just like throws
Java clause. Make sure to keep in mind that @throws
is only for Java consumption.
You may also want to take look at scala.util.control.Exception. It contains all sorts of goodies for dealing with exceptions.
Source.fromFile
calls java.io.FileInputStream.open
, which throws a FileNotFoundException
if you give it a nonexistent file.
Source.fromFile
doesn't catch this, so it will be seen in your code.
I suspect many of the other exceptions possible in the java.io
package are similarly unhandled, but apparently undocumented.
精彩评论