Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala io.Source.FromFile return any kind of exception?

I was reviewing my code for the last time 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?

like image 717
DDB Avatar asked Oct 11 '22 04:10

DDB


1 Answers

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/catchs 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.

like image 162
pedrofurla Avatar answered Dec 15 '22 15:12

pedrofurla