Scala encourages a coding style that lessens the need for exceptions and exception handling. But exceptions are still used, especially where Scala interacts with Java code, where use of exceptions is more prevalent.
Unlike Java, Scala does not have checked exceptions, which are now regarded as an unsuccessful design. Java’s checked exceptions are treated as unchecked by Scala. There is also no throws
clause on method declarations. However, there is a @throws
annotation that is useful for Java interoperability.
Scala treats exception handling as just another pattern match (???), allowing us to implement concise handling of many different kinds of exceptions.
Code Example
// TryCatch.scala
package com.brown
import scala.io.Source
import scala.util.control.NonFatal
/**
* Created by BrownWong on 2016/10/11.
*/
object TryCatch {
def main(args: Array[String]) = {
countLines("haha.txt")
}
def countLines(fileName: String) = {
var source: Option[Source] = None
try {
source = Some(Source.fromFile(fileName))
val size = source.get.getLines.size
println(s"file $fileName has $size lines")
} catch{
case NonFatal(ex) => println(s"Non fatal exception! $ex")
} finally {
for (s <- source) {
println(s"Closing $fileName")
s.close()
}
}
}
}
haha.txt
nima
niba
niye
ninai
haha
bye
!
output
file haha.txt has 7 lines
Closing haha.txt
Note the catch
clause. Scala uses pattern matches to pick the exceptions you want to catch
. This is more compact and more flexible than Java’s use of separate catch
clauses for each exception. In this case, the clause case NonFatal(ex) => …
uses scala.util.control.NonFatal
to match any exception that isn’t considered fatal.
This is a widely used idiom; use a
for
comprehension when you need to test whether anOption
is aSome
, in which case you do some work, or is aNone
, in which case you ignore it.
Ref